Why is the use of `!important` discouraged? - css

Several answers tagged css discourage the use of !important in favor of specificity. Why?

There is actual math you can use to predict, control, and reverse-engineer the impact of CSS rules. By using !important you're breaking that. Look at this JS fiddle for example, which doesn't use !important: http://jsfiddle.net/hXPk7/
If you use Firebug or Chrome dev tools to inspect the title element where it says "Richard", you should see these rules, in this order:
/**************************/
/* /hXPk7/show/ (line 20) */
/**************************/
#myExample #title .name {
color: yellow;
}
/********************************************************/
/* /hXPk7/show/ (line 14) - Inherited fromdiv#myExample */
/********************************************************/
#myExample {
color: blue;
}
Note that this is not the order in which they appear in the CSS stylesheet - instead they are ordered in decreasing order of their specificity. The ones which take precedence are listed first, and the others (whose rules are overridden by more specific rules) probably have a property crossed out. This demonstrates that specificity makes it easy to trace (debug?) where an element is getting its CSS properties from.
Now, compare with this JS fiddle - which is effectively the same, but has a single new rule which now uses !important: http://jsfiddle.net/hXPk7/1/
Inspect the same element using Firebug or Chrome dev tools, and you'll see something like this:
/**************************/
/* /hXPk7/1/show/ (line 20) */
/**************************/
#myExample #title .name {
color: yellow;
}
/**************************/
/* /hXPk7/1/show/ (line 26) */
/**************************/
span {
color: black !important;
}
/********************************************************/
/* /hXPk7/1/show/ (line 14) - Inherited fromdiv#myExample */
/********************************************************/
#myExample {
color: blue;
}
Again, the rules are ordered according to their specificity - but note that this time, while the most specific rule which is listed first specifies a color of yellow, the browser instead renders the text as black! This is because the !important declaration has broken the normal behavior of specificity, taking precedence in a way which can be challenging to trace. Imagine a more realistic web site, with potentially hundreds of rules, and the one controlling the color isn't obvious to find, or to change.
Now, maybe this is a problem with the developer tools, but I think it reflects the fact that !important takes a normally easy-to-predict system of precedence and makes it more challenging. Maybe there are times to use it, but it should not be the first tool you reach for when writing CSS.

Related

Nesting CSS selectors without increasing specificity

Let's take these three selectors, sorted from the highest specificity to the lowest:
.special-section p { }
.weird-font { }
p { }
Many CSS gurus recommend against nesting like in the first selector .special-section p, because its specificity is high enough that you can't override it with a simple class like .weird-font. I would like to find a way to still achieve nesting like in .special-section p, but without increasing specificity. Something like this:
.weird-font { }
.special-section p /* with hack to decrease specificity */ { }
p { }
Use case:
It's pretty safe to apply defaults for typography and such document-wide using simple selectors like p. However, I would like to change those defaults for a particular section, similar to .special-section p, without having to use hacks to increase the specificity of selectors like .weird-font. I would rather use a hack to decrease the specificity of .special-section p than use a hack to increase the specificity of .weird-font. Is there a way to do this?
You can't decrease the specificity, but you can add an even more specific selector for the exception.
.weird-font, /* Normal weird font */
.special-section p.weird-font /* Override for special section */
{ }
But as you can see, it's a sliding scale. So those gurus are probably right. If you would remove .special-section p, and instead give those P's their own selector .special-section-para or something, then you won't have this problem.
But personally, I don't mind having to add an exception like the one above now and then. I think the whole specifity thing is there for that purpose, and if you need a more specific selector to style something, to me that seems the right thing to do.
A commonly heard solution is to use !important. The problem with !important is that there is only one level of override. If you make a more specific selector, you can override it again with a still even more specific selector. After using !important, you're out of options. More importantly, using !important may interfere with special style sheets that a user may have for increased readability. For that reason I never use !important in a situation like this.
But then again, I don't consider myself a CSS guru. ;)
These days, in 2018, this is getting close to possible.
First of all, CSS4 will have a way that allows you to create more specific selectors without increasing specificity:
:where(.special-section) p {
color: red;
}
This will set the paragraph color inside .special-section to red, but with a specificity of 001 (i.e. the same specificity that a plain p selector would have).
The spec still calls this special pseudo-class :something(), but chances are it's going to be called :where(). (Side note: I really want this to be known as the "honey badger selector").
But that's still in the future.
However, there is actually a way to achieve this today, if you don't have to support IE anymore (or are happy with less-than-perfect fallbacks), and that is by using custom properties a.k.a. CSS variables.
So you want this:
.special-section p { color: red; }
.weird-font { color: magenta; }
p { color: green; }
but with the first part having a specificity that's lower than any selector with a class in it. You can do it like this:
.special-section p { --low-specificity-color: red; }
.weird-font { color: magenta; }
p { color: var(--low-specificity-color, green); }
If you run the below snippet in a modern browser, you should notice that the second paragraph is red, because it's in a special section, but the third paragraph is magenta, because it's .weird-font -- even though .weird-font has 010 specificity and .special-section p has 011.
.special-section p { --low-specificity-color: red; }
.weird-font { color: magenta; }
p { color: var(--low-specificity-color, green); }
<p>This is a paragraph.</p>
<section class="special-section">
<p>This is a paragraph inside a special section.</p>
<p class="weird-font">This is a paragraph with a weird font inside a special section.</p>
</section>
<p class="weird-font">This is a paragraph with a weird font.</p>
<div class="weird-font">This is a div with a weird font.</div>
This works because while the --low-specificity-color is changed with 011 specificity, it is only applied with a 001 specificity.
As a CSS guru, I bemoan the idea of throwing out everything Selectors has to offer just to avoid specificity issues. That's not to say I don't believe the specificity mechanic is flawed, but surely there are less dramatic workarounds for it.
First off: no, you can't decrease the specificity of a selector. Selectors doesn't provide any features with negative specificity levels that would decrease specificity in such a manner. The lowest you can go is *, which has zero specificity (i.e. it does not make a complex selector any more or less specific).
So your only recourse on the selector level is to increase it. Whether you can do this without using hacks depends on your definition of "hack".
The following is what I would consider a hack, because it makes use of a syntactically legal but semantically nonsensical selector like :not(_) that has no obvious purpose but to add a type selector's worth of specificity to a complex selector (which is far from obvious especially to the uninitiated):
.special-section p { }
.weird-font, :not(_).weird-font { }
The following is not what I would consider a hack, because it's something you would do normally anyway. Pretty much the only "issue" with it is that it's an apparent repetition of the lone class selector:
.special-section p { }
.weird-font, .special-section p.weird-font { }
If you consider any sort of extraneous selector for the sake of increasing specificity a hack — which is a perfectly reasonable POV, make no mistake — then the next best thing that isn't a hack is !important.
Personally, I would choose a specificity hack. !important has, ahem, important repercussions that don't come with a specificity hack — remember that !important and specificity have different semantics. For example, you cannot override an !important declaration with an inline style or JavaScript unless they are marked important as well.1
1 In fact, this was my response to Lea Verou when she had a discussion on Twitter some time ago regarding specificity hacks versus !important.
I like to be as specific as is currently necessary. I do like to leave room for future CSS changes, so don't go as specific as possible for the sake of it, such as:
.great-grandfather .grandfather .father .child { }
I will if I have to of course. But taking the example above, if I wanted to override the .child for a particular element that uses this class which has styling which might be like this:
.child {
color: black;
}
I'd go one parent above to override it, if possible:
.father .child {
color: white;
}
Further down the line, if an element on a particular page uses the .child class and in this case I need to override both the .father .child, I'll go one more level of specificity:
.grandfather .father .child {
color: red;
}
Doing it this ensures you don't need to use !important... Which I avoid like the plague as much as possible!

What's the standard way to deal with unsupported CSS expressions?

What does the CSS standard say about unsupported expressions? How should a browser deal with them? How do actual browser implementations deal with them?
I'm implementing a CSS property optimizer (for a minifier project), and we want to leave CSS fallbacks intact. Our goal is to optimize the CSS as much as possible but in such a way that it should render exactly the same as the original.
This is why it's essential for me to understand how these things work.
Simple properties
For simple properties, it's really easy.
Let's say we have this:
div {
color: #f00;
color: rgba(1,2,3,.4);
}
In this case, if the browser doesn't support rgba then the first declaration #f00 wins. There is no question here.
Shorthands
However, how does it work with shorthand properties?
Here's some code:
div {
background: #f00;
background: rgba(1,2,3,.4);
}
How does the browser render this if it doesn't understand rgba? As you know, the syntax of background is: background: <color> <image> <repeat> <attachment> <position>; and such a shorthand declaration overrides any of the 5 fine-grained declarations that came before it; so the difficulty lies in which one of the 5 fine-grained properties the browser tries to assign the unknown token to. I have several possibilities in mind:
the browser decides it doesn't understand the latter declaration at all and drops it entirely
the browser thinks that rgba(...) represents a background-image and even though it doesn't know what to do with it, clears out the previous background-color as well
the browser thinks that rgba(...) represents a background-color and since it doesn't understand it, falls back to using #f00 instead
Let's make it even more interesting, say we have this:
div {
background: #fff url(...) no-repeat;
background: rgba(1,2,3,.4) linear-gradient(...) repeat-y;
}
How does a browser interpret this CSS snippet, ...
if the browser doesn't understand rgba?
if the browser doesn't understand linear-gradient?
if the browser doesn't understand repeat-y?
if the browser doesn't understand any two of the three?
if the browser doesn't understand any of the three?
The parsing rules in section 4.2 of the CSS2.1 spec speaks in terms of declarations, which refer to entire property-value pairs, regardless of whether the properties are shorthand or not:
Illegal values. User agents must ignore a declaration with an illegal value. For example:
img { float: left } /* correct CSS 2.1 */
img { float: left here } /* "here" is not a value of 'float' */
img { background: "red" } /* keywords cannot be quoted */
img { border-width: 3 } /* a unit must be specified for length values */
A CSS 2.1 parser would honor the first rule and ignore the rest, as if the style sheet had been:
img { float: left }
img { }
img { }
img { }
A user agent conforming to a future CSS specification may accept one or more of the other rules as well.
Notice that the third example shows the use of an illegal value for the background shorthand property resulting in the entire declaration being ignored.
Although the spec speaks of illegal values, as far as an implementation is concerned an unrecognized value and an illegal value are the same thing, since either way the implementation doesn't know what to do with such a value.
So the answer to the first part of your question is
the browser decides it doesn't understand the latter declaration at all and drops it entirely
And the answers to the second part are all the same: the latter declaration is ignored entirely.
As far as I know, if a browser cannot understand even a part of an expression, then it handles the property as syntactically wrong, and ignores the whole line.

How are unknown/invalid pseudo-classes in CSS selectors handled?

What does this CSS selector should point to? AFAIK :bar pseudo-class does not exist...
.Today_s_foo:bar
{
font-size: 21px;
font-family: "Ubuntu";
}
Normally it should invalidate the whole rule, which may be important when using multiple selectors in one rule, see simple example: http://jsfiddle.net/S56xM/
HTML:
<div>Hello!</div>
CSS:
div, div:foobaresque { font-size: 100px; }
You will see that the div { font-size: 100px; } "sub-rule" is not applied, even if our mind tells us it would be applied.
Per the current specification for parsing errors in selectors: "the entire rule in which the selector is used is dropped." See also this part of the spec for an example of the consequences.
By "rule" it means every property setting inside the {brackets} will be ignored if any part of the selector is parsed as invalid.
Correction applied
The rules in .Today_s_foo will not be set on any working browser.
I thought it was listed as an Unrecommended hack on http://www.javascriptkit.com/dhtmltutors/csshacks3.shtml
IE
.Today_s_foo:IE6 /* IE6 hack */
but its not there.

How do you read !important in CSS? [duplicate]

This question already has answers here:
What does !important mean in CSS?
(5 answers)
Closed 3 years ago.
How is the CSS attribute property !important read?
Is it really important, exclamation mark important, ...?
Answer: From the answers below, it seems to be read simply important, or bang important.
an "!important" declaration (the delimiter token "!" and keyword
"important" follow the declaration) takes precedence over a normal
declaration.
http://www.w3.org/TR/CSS2/cascade.html#important-rules
Basically, where two style rules are the same... it gives the one marked !important greater importance and will apply those styles.
Example
div{
opacity:0 !important;
}
div.jason{
opacity:1;
}
The first rule would be applied even though the second rule is more specific (one element + one class as opposed to one element)
Note: IE6 ignores !important when you have two of the same property and one of them is important - it'll always apply the last declaration, whether or not it was marked important. **Added from #BoltClock's comment below.
Warning: !important is a hammer that should only be used when absolutely necessary. Almost always, it is better to use more specific selectors to achieve greater specificity and have your styles applied the way you want. !important can make it very difficult for future developers to find and make changes to your code.
One good use case: !important is great for user-defined styles, where a user wants to manipulate Web site pages in specific way in his browser (say make all the backgrounds black and the text yellow). Without having to worry about specificity, the user can add styles to certain elements (like body) and make the styles render.
Just "important" or "bang important." The ! is definitely not a negation in this case.
It's not a tag, it's a keyword.
body { color: red !important; } means, in English, "The text-color of red is important".
In terms of how CSS sees it, it applies more "weight" to that declaration, so it will be (far) more likely to be the applied style.
For an example of this, we can use
p { color: red; }
p.blue { color: blue; }
Now, any p with a class of blue will show blue text, all the others will show red text.
If we change it to this...
p { color: red !important; }
p.blue { color: blue; }
They will all show red text (even if they have a class of blue), as we've given more important to the first selector.
I like to think of it as "NOT important".
p {
color: red !important; /* The rest is NOT important for this CSS property. */
}
Meaning that everything else from that declaration and on is NOT important and should not be taken into account. The idea came from the usage of the "!" character as a boolean NOT in many programming languages. This way the !important makes sense as you read it.
I guess I read the ! as "very".
p { color: red !important }
I read as "Paragraphs have the color red, which is very important.

Repeated Heading Selectors

With the recent launch of http://csslint.net, I'm questioning some ways I've constructed my stylesheets in the past. The following method is one that I've used recently:
/* Fonts */
h1 { font-size:20px }
p { font-size:12px }
/* Colors */
h1 { color:green }
p { color:grey;
background-color:white }
/* Margins */
h1 { margin:0 }
p { margin:0 0 5px }
The problem, according to the linter, is that I'm re-declaring heading selectors over and over again. The reason of course is to keep logical separation between types of rules. If I wish to change colors, I would visit the colors region. If I wish to change dimensions, I would visit the dimensional areas.
Is CSSLint worried that I may be in danger of overwriting styles, thus wasting chars, or are there performance issue related to how many blocks contribute to the overall presentation of heading elements?
Is this a bad practice, or merely a false-alarm?
Styles get computed for all h1s and all ps either way. The overhead of selector matching is little compared to the equally-negligible performance "impact" of actually computing and rendering the styles.
I'm guessing what you think CSS Lint is worried about is the case. In fact, I kinda like how you organize your styles myself, and don't see any other problems than overwriting declarations by accident.
From their documentation -
Heading elements should have a consistent appearance across a site.
I think it is more to do with usability/consistency rather than performance. A heading of size 20px on one page and 14px on another just looks unprofessional.

Resources