Resetting and Overrulling CSS under a certain element - css

I have element that could be injected into any page using a Firefox Addon.
Naturally, it and its ancestors are affected by the CSS rules defined on that page.
I can get so far by simply being explicit about every attribute, but even then my declarations may be overridden by an earlier declaration on the page with greater specificity.
Without making a huge mess of needlessly specific selectors and hanus use of !important, how could I go about resetting all elements' attributes under a given element (div#my_root_container_element) and ensure that my declarations under this parent element apply.
Using an iFrame is one option, but I would rather avoid it if possible - is there another way? Given the application, solutions need only work in Firefox.
Thanks.

Obviously, it seems like this aims to override the "specificity" which is core to CSS in general, but this is the closest I remember ever seeing someone attempt it. It seemed somewhat reputable at the time coming from someone involved with the YUI project:
http://developer.yahoo.com/yui/reset/#code

Using SASS, it's not too unpalatable nesting everything under a div with an ID to achieve sufficient specificity, which is the solution I've opted for.
That said, any !important declaration made in the page CSS will overrule my styles.

Related

In CSS, are !important declarations more or less efficient than non !important ones? [duplicate]

I hate them, it defies the cascading nature of CSS, and if you don't use them with care you end up in a loop of adding more !important.
But I want to know are they bad for performance?
EDIT
From the (fast) replies I can conclude it won't have a (significant) impact on performance.
But it's nice to know, even if it's just as an extra argument for discouraging others ;).
EDIT 2
BoltClock pointed out that if there are 2 !important declarations the specs says it will pick the most specific one.
It shouldn't have any discernible effects on performance. Seeing Firefox's CSS parser at /source/layout/style/nsCSSDataBlock.cpp#572 and I think that is the relevant routine, handling overwriting of CSS rules.
It just seems to be a simple check for "important".
if (aIsImportant) {
if (!HasImportantBit(aPropID))
changed = PR_TRUE;
SetImportantBit(aPropID);
} else {
// ...
}
Also, comments at source/layout/style/nsCSSDataBlock.h#219
/**
* Transfer the state for |aPropID| (which may be a shorthand)
* from |aFromBlock| to this block. The property being transferred
* is !important if |aIsImportant| is true, and should replace an
* existing !important property regardless of its own importance
* if |aOverrideImportant| is true.
*
* ...
*/
Firefox uses a top down parser written manually. In both cases each
CSS file is parsed into a StyleSheet object, each object contains CSS
rules.
Firefox then creates style context trees which contain the end values
(after applying all rules in the right order)
From: http://taligarsiel.com/Projects/howbrowserswork1.htm#CSS_parsing
Now, you can easily see, in such as case with the Object Model described above, the parser can mark the rules affected by the !important easily, without much of a subsequent cost. Performance degradation is not a good argument against !important.
However, maintainability does take a hit (as other answers mentioned), which might be your only argument against them.
I don't think that !important is inherently bad in terms of how quickly the browser matches rules (it does not form part of the selector, only part of the declaration)
However, as has already been stated, it will reduce the maintainability of your code, and thus likely cause it to grow unnecessarily in size due to future changes. The usage of !important would also likely reduce developer performance.
If you were being really picky, you could also say that !important adds 11 extra bytes to your CSS file, this isn't really much, but I guess if you have a fair few !importants in your stylesheet it could add up.
Just my thoughts, unfortunately I couldn't find any benchmarks on how !important could affect performance.
!important has its place. Trust me on that one. It's saved me many times and is often more useful as a short-term solution, before a longer and more elegant method to your problem can be found.
However, like most things, it's been abused, but there's no need to worry about 'performance'. I'll bet one small 1x1 GIF has more of a performance hit on a web page than !important would.
If you want to optimize your pages, there are many more !important routes to take ;) ;)
What's going on here behind the scenes is that as your CSS is being processed, the browser reads it, encounters an !important attribute, and the browser goes back to apply the styles defined by !important. This extra process might seem like a small additional step, but if you are serving up many requests then you will take a hit in performance. (Source)
Using !important in your CSS usually means developer narcissistic & selfish or lazy. Respect the devs to come...
The thinking of a developer when using !important:
My rocking CSS is not working... grrrr.
What should I do now??
And then !important yeah.... now it's working fine.
However its not a good approach to use !important just because we did not manage the CSS well. It creates lots of design issues -- which are worse than performance issues -- but it also forces us to use many extra lines of code since we are overriding other properties with !important and our CSS becomes cluttered with useless code. What we should do instead is first manage the CSS very well, and not let properties override one another.
We can use !important. But use it sparingly and only when there is no other way out.
I agree with you on not using it because it's bad practice, regardless of performance. On those grounds alone, I'd avoid using !important wherever possible.
But on the question of performance: No, it shouldn't be noticeable. It might have some effect, but it should be so tiny you should never notice it, nor should you worry about it.
If it is significant enough to be noticable then you've likely got bigger problems in your code than just !important. Simple use of a normal syntax element of the core languages you're using is never going to be a performance issue.
Let me answer your question with a retorical question in return; an angle that you probably didn't consider: Which browser do you mean?
Each browser obviously has its own rendering engine, with its own optimisations. So the question now becomes: what are the performance implications in each browser? Perhaps !important performs badly in one browser but really well in another? And perhaps in the next versions, it'll be the other way round?
I guess my point here is that we as web developers shouldn't think about (or need to think about) the performance implications of individual syntax constructs of the languages we're using. We should use those syntax constructs because they're the right way to achieve what we want to do not because of how they perform.
Performance questions should be asked in conjunction with the use of profilers to analyse where the pinch-points are in your system. Fix the things that are truly slowing you down first. There are almost certain to be far far bigger issues for you to fix before you get down to the level of individual CSS constructs.
It does not noticeably affect performance. It does however reduce the maintainability of your code, and therefore is likely to degrade performance in the long run.
Having had to use !important several times before, I have personally noticed no demonstrable performance hit when using it.
As a note see the answer to this stack question for a reason you might want to use !important.
Also I'll mention something that everyone else has failed to mention. !important is the only way to override inline css short of writing a javascript function (which will effect your performance if even only a little bit). So it could actually save you some performance time if you need to override inline css.
hmm... !important or !!important?
Let's go through this step by step:
The Parser has to check for !important for each property, regardless of whether you use it or not - so performance difference here is 0
When overwriting a property, the parser has to check whether the property being overwritten is !important or not - so performance difference here is 0 again
If the property being overwritten is !!important, it has to overwrite the property - performance hit of -1 for not using !important
If the property being overwritten is !important, it skips overwriting the property - performance boost of +1 for using !important
If the new property is !important, the parse has to overwrite it regardless of the property being overwritten is !important or !!important - performance difference 0 again
So I guess !important actually has better performance as it can help parser skip many properties that it won't skip otherwise.
and as #ryan mentions below, the only way to override inline css and avoid using javascript... so another way to avoid an unnecessary performance hit
hmm... turns out out that !important is important
and also,
using !important saves a lot of time for a developer
sometimes saves you from redesigning the whole css
sometimes html or the parent css file is not in your control, so it saves your life there
obviously prevents !important elements from being accidentally overwritten by other !!important elements
and sometimes browsers just don't pick the right properties, without being too specific in selectors, so using !important really becomes important and saves you from writing tonnes of specific css selectors in your css. so i guess even if you use more bytes for writing !important, it could save you bytes in other places. and we all know, css selectors can get messy.
So I guess using !important can make developers happy, and I think that's very important :D
I can't foresee !important impeding performance, not inherently anyway. If, however, your CSS is riddled with !important, that indicates that you've been over qualifying selectors and being too specific and you've run out of parents, or qualifiers to add specificity. Consequently, your CSS will have become bloated (which will impede performance) and difficult to maintain.
If you want to write efficient CSS then you want to be only as specific as you need to be and write modular CSS. It's advisable to refrain from using IDs (with hashes), chaining selectors, or qualifying selectors.
IDs prefixed with # in CSS are viciously specific, to the point where 255 classes won't override an id (fiddle by: #Faust). ID's have a deeper routed problem too though, they have to be unique, this means you can't re-use them for duplicate styles, so you end up writing linear css with repeating styles. The repercussion of doing this will vary project to project, depending on scale, but maintainability will suffer immensely and in edge cases, performance too.
How can you add specificity without !important, chaining, qualifying, or IDs (namely #)
HTML
<div class="eg1-foo">
<p class="eg1-bar">foobar</p>
</div>
<div id="eg2-foo">
<p id="eg2-bar">foobar</p>
</div>
<div class="eg3-foo">
<p class="eg3-foo">foobar</p>
</div>
CSS
.eg1-foo {
color: blue;
}
.eg1-bar {
color: red;
}
[id='eg2-foo'] {
color: blue;
}
[id='eg2-bar'] {
color: red;
}
.eg3-foo {
color: blue;
}
.eg3-foo.eg3-foo {
color: red;
}
JSFiddle
Okay, so how does that work?
The first and second examples work the same, the first is literally a class, and the second is the attribute selector. Classes and Attribute selectors have identical specificity. .eg1/2-bar doesn't inherit its color from .eg1/2-foo because it has its own rule.
The third example looks like qualifying or chaining selectors, but it's neither. Chaining is when you prefix selectors with parents, ancestors, and so on; this adds specificity. Qualifying is similar, but you define the element the selector's applying to. qualifying: ul.class and chaining: ul .class
I'm not sure what you'd call this technique, but the behavior is intentional and is documented by W3C
Repeated occurrances of the same simple selector are allowed and
do increase specificity.
What happens when the specificity between two rules is identical?
As #BoltClock pointed out, If there's multiple !important declarations then
spec dictates that the most specific one should take precedence.
In the example below, both .foo and .bar have identical specificity, so the behavior fallsback to the cascading nature of CSS, whereby the last rule declared in CSS claims precedence i.e. .foo.
HTML
<div>
<p class="foo bar">foobar</p>
</div>
CSS
.bar {
color: blue !important;
}
.foo {
color: red !important;
}
JSFiddle

How to reset all styles of a div and decedents back to Chrome defaults

I'm not sure this is possible, but id like to set all user styles back to chrome defaults for div and descendants.
I'm building a Chrome plugin that creates a popup on any web page, however due to the fact every page has a plethora of custom styles, trying to track down every inconsistency and overwrite it with my divs (and descendants) custom style, it is becoming a nightmare.
Every time I think I've covered all bases another site implements something else that needs to be overridden.
What would be the easiest approach to standardize my popup in this situation?
One approach I can think of is to (bite the bullet) and get a hold of the the default Chrome CSS styles and implement them into a series of catch all descendant selectors, however surely there is a better way.
If you want to be absolutely sure that the styling of your elements is not affected by the web-page's CSS, there are 2 possible solutions:
Use an iframe to implement your popup. (This solution is "safe" and simple enough, but based on the kind of interaction between the popup and the web-page it might become cumbersome.)
Utilize the Shadow DOM. (This is probably the "proper" solution, but the implementation might be a little more complicated.)
Some resources regarding the 2nd solution:
An introductory tutorial.
An actual example of incorporating the "Shadow DOM" concept into a Chrome extension:
RobW's Display Anchors extension
There is a third option worth discussing and rejecting, which is to reset all the style properties of the div and its descendents to its default value. Pseudo-code:
#my-div, #my-div * {
#for-every-css-property {
%propertyName: initial !important;
}
}
This answer shows an attempt at such a solution. It uses specific values instead of initial which will work in older browsers without the initial keyword, but will not correctly reset elements which have a different default from the base (e.g. user566245 mentions that textarea elements should have a border).
Issues:
Unfortunately initial is not actually the browser's default value.
If we don't use !important above then there is a risk that the page might have provided a rule with a more specific elector which overrides our own. For example if the page specified properties for table > tr > td then this would be applied over our rule because that selector is more specific than #my-div *.
Since we do use !important, any custom styling we want to do after the reset must also use !important on every property.
If the page happens to inject any additional CSS styles after ours that uses !important then these can override our reset.
It is rather inefficient. We are asking the browser to apply a huge bunch of CSS rules to every element under our div.
Vendor-specific properties should also be reset. (E.g. -webkit-animation-name.)
If new CSS properties come into existence in future, you will need to update your list.
Whilst this solution can be applied to current browsers, it is rather horrible, so roll on Shadow DOM! I would recommend the <iframe> solution in the meantime.
I don't know if anyone has tried this, but a more efficient solution might be to use Javascript to detect what site-defined CSS properties could be problematic, and reset only those.

Update existing design of a website, use of CSS

I'd like to get opinions if this plan is worthwhile or not.
I have an existing site, and some elements have a CSS class defined.
I thought I would append each element that has a class with a new class:
<div class="existingClass">
would turn into:
<div class="existingClass newClass">
Then, if I want to override any attributes in "existingClass", I would do so in "newClass" (because the last class attributes are taken?).
I figure this way, nothing would break, so I do not risk anything because I am not removing "existingClass".
Any problems with this plan?
First know what is in the existingClass. Write newClass in such a manner that it won't break the layout. For knowing what is in the existingClass use tools like firebug to save time.
Indeed this seems to be a good approach, if you don't want to mess editing the already written CSS.
What you must master are CSS precedence rules, also known as CSS specificity.
Some good articles about it:
Specifics on CSS Specificity.
CSS Specificity: Things You Should Know
This is important because when you want to change a style, that chance will be visible only if you follow appropriately those guidelines. If you don't, then you'll face some troubles when rendering your page.

CSS Specificity Filter

This is a long shot, but is there a tool available that optimizes CSS selectors by removing unneeded specificity?
I find that when I write CSS, I deliberately make my selectors more specific than necessary to avoid conflicts and for quasi-documentation.
It would be great if there were a tool that could analyze a given group of rules, determine their "uniqueness" in terms of overlap with other rules, and then strip away any unnecessary specificity.
I can't even begin to imagine how a tool developer would approach all of the scenarios this would require, but I've been blown away by others' ingenuities in this area before and figured it was worth asking.
Update:
I've added a bounty to this question, and the more I think about it, the more I realize how valuable a CSS Specificity Filter would be.
For example, when working with Nested Rules/Selectors in Sass and LESS, excessive nesting is a common and well-known antipattern that can easily lead to overly specific selectors.
There's a good illustration of this in the excellent TutsPlus course Maintainable CSS with Sass and Compass:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass will follow these nesting instructions and produce the following CSS output, raising no objection to any unneeded specificity:
body div.container p a {
color: purple;
}
If a Specificity Filter did/does exist, however, it would create potential benefits for CSS developers:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
Points in CSS Specificity
Tool to See CSS Specificity
Tool for Cleaning Up CSS
Order by CSS Specificity
Top 5 Mistakes of Massive CSS
Google: Efficient CSS Selectors
Procssor
Clean CSS
CSS Tidy
You could attempt to take a different approach, try to write your selectors as small (low specificity) as possible. and only make them more specific when needed.
With that way of working you don't need a tool.
Just going to throw this out there-- it doesn't 'answer' your question,but it's a tool I like to spread the word about for people who do a lot of css programming: Firebug.
If you're not familiar with it, it's a tool for web browsers. You pull up your page once it's installed, right click and select 'Inspect Element.' It will show you all css affecting different elements on your page, and is useful for creating clean, precise css code. Also it makes it easier to see instant updates on what your page would look like with slight modifications. It will inform you of useless css code that's being overridden by other css code.
ALSO! Firebug now is available for almost all browsers. Not just Firefox. Personally, I'm partial to using it in Chrome.
We really can't do without specificity because it is the only thing that saves you when you have two or more rules colliding. Specificity brings sanity to the whole jumbled CSS rule, so it is more of a blessing than curse. Some of the stuff you talked about, like the CSS selector, can be done using Firefox/Firebug. I'm more disturbed by browser compatibility.
Actually there's a way you can do this using HTML5 and CSS3. The standard technique is to specify elements using the HTML 5 attribute "data-" and then do CSS selection for this attribute. This isn't the purpose of the attributes, but you can customly specify some elements that you can use to even switch the theme of a site.
So, for example, you can end up creating your specificity filters manually in CSS, by specifying
<b data-specificity=2>test</b>
where data-specificity only matches to parents above.
UPDATE:
Alright, so for example, let's say you have a paragraph class, but you want to specify which parent, or how many parents the paragraph can inherit properties from. You would use rules for each potential parent that can be inherited from:
p[data-specificity="1"]{
color:red;
font-family:verdana;
text-decoration:underline;
}
p[data-specificity="2"]{
color:black;
font-family:arial;
}
div.container > *[data-specificity="2"] {
font-family:impact;
color:blue;
text-decoration:underline;
}
So these rules mean that any p tag which is a direct child of the div container and has specificity 2, is allowed to inherit properties from the div container. The blue color of the div gets inherited by the p with data-specificity 2.
Here's a JSFiddle where you can see this!
The idea is that like this, using HTML5, you can control exactly which elements are allowed to inherit which properties. It's a lot of extra code to write (for both child and parent elements) but you can use this to get rid of some unnecessary specificity
I've never actually seen anyone use this method in practice, I pretty much just cooked it up for you, but I think it could be very useful, what do you think ?

Should I avoid using !important in CSS?

Sometimes !important is useful, for example if I have defined common style for all links on the site (selector, say, a), but when I want to override some rules I have the following choices:
Use more specific (longer) selector
Use !important
Which way is better and may be there are some guidelines?
Use !important very, VERY sparingly -- it overrides just about everything, even inline styles, and messes in a less-than-obvious way with the "cascade" of style rules that gives CSS its name. It's easy to use badly, and tends to multiply, particularly when misused. You can easily end up with a element with !important rules that you want to override, at which point you often have to either refactor your styles, or use another !important rule and contribute to the problem.
And once it's spread and you're using it everywhere, you're back up in the same situation you'd be in without it (difficulty in specifying elements specifically enough to override other styles), but you also don't have !important anymore cause everything else is using it too.
When faced with a situation where !important looks appealing -- or worse, one where it's already in use and spreading -- prefer to refactor your CSS if you can. (Frankly, if you need !important outside of a user style sheet, it's usually because your selectors are already way too specific, and/or you're not taking advantage of the C in CSS.) You'd do better to define your basic styles as close as possible to the html or body elements, and when you want to override, use as little specificity as you can get away with. That way, you have plenty of room to make changes. Usually there's a reason you want to override a style, and those cases can quite often be boiled down to a class name, a particular section of the page (read: a particular parent element), etc.
(The only real exception that springs to mind is if the styles you're overriding are effectively out of your control. (If you use a framework that has very strong opinions on how your page should look, for example, you might find it annoyingly difficult to override anything. I've worked with applications that actually inserted their own inline styles, where nothing but an !important rule could override them.) If you don't have full access to the code, overriding and refactoring can easily be more trouble than they're worth. You can use !important to claw back some control, as long as you're aware of the consequences.)
What i can say is that you should try to avoid it as much as you can because it means that there are redundant code, and give an indication that the CSS and styles are not well structured.
But in some cases its a must to use it and no way to avoid.
So just do your best.
Avoid it when you can as this is what most advocate but at the same time it is important.
Have a look at:
The importance of !important in CSS

Resources