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
Related
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
I've noticed that a lot of css style recipes are often stated like this:
div#id_name {
blah: blah;
}
But since IDs are unique, what's the point of sticking "div" in front of #id_name? Is there any advantage over the following snippet?
#id_name {
blah: blah;
}
I would argue that the latter is superior because you might decide to make the id_name element into something besides a div.
This is primarily done to advance specificity and to hint the document as to what type of element #id_name is.
First, specificity:
Specificity determines which styles are actually applied to your element. The more specific you are in calling your element out, the more priority that block of properties takes over another.
For example:
Given HTML
<div id="id_name">
Look at this blue text!
</div>
With CSS
div#id_name {
color: red;
}
#id_name {
color: blue;
}
Results in
This will render a div with red text as opposed to blue text. This is beneficial when writing a framework if you want to guard your styles from being arbitrarily overwritten by local styles.
Secondly, hinting:
Oftentimes, CSS is an afterthought. It's a shame, too, as it's gotten increasingly more powerful and has taken many of the responsibilities previously reserved for client-side scripting languages like JavaScript. There is no implicit inheritance in CSS, rather it's explicit via a long declaration.
What I'm talking about with this is that you don't see
div {
.my-class {
/* RULES! */
}
#my-id {
/* RULES! */
}
}
as a part of CSS unless you're using a precompiler like LESS or SASS. Hinting a document with the element name instead of only the id or class allows for much greater readability for not only future you, but any collaborators you may have on the project.
And finally:
Sometimes it just doesn't make sense to not add a an element guard to your rule. If I have a rule that sets things like height, width or padding, I wouldn't want that same rule applied to a span. I would rather see it fail loud than silent to prevent rules being applied that have no place being there. It can cause messy and unexpected results given the exact scenario you described.
In addition, there's no guarantee that #id-name won't be re-used on a later page for an element that is not a div in the scenario you gave. So there's that, too.
Using ID's have a very strict specificity issue. Realistically, according to the standards, you can only use an ID once in any given HTML document. That doesn't mean you can't use ID's as styling selectors, though, it does come with dangerous pitfalls in larger projects. They're fine if you're using them as targets in Javascript. Go crazy.
ID selectors are very, very specific in targeting elements and in return, you end up with problems later down the line dealing with CSS specificity. Class selectors are reusable and have much looser specificity. Styling with ID's doesn't have anything different that a class selector doesn't have, so why use them if they're causing specificity issues? Read this and this. They are both fantastic articles on why ID's are not cool for CSS. It is a personal preference, but, making your CSS very specific is a front-end disaster in all real-world cases web development.
So, to answer your question properly, adding div at the start of and id selector, like div#id_name means you can only apply that id to a <div> element. You couldn't add it to a <span>, or any other element for example, which is an insanely restrictive method of styling in CSS. If you just use #id_name, you can apply this selector on any element instead.
The only difference is that div#id_name has higher specificity. This is seldom relevant, and there are other ways to make a selector more specific. People may include the element (tag) name for documentation purposes, but then they take the risk that was referred to in the question: someone might change the div to, say, p and forget to modify the CSS selector(s).
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 ?
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
I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)