Some things are !important;
DISCLAIMER: As the comments below point out, this is not an example of good HTML or CSS, it's just a tip on how you can make sure that your style is used by declaring it !important
We have this situation:
- We want to style all p elements inside a div#container
- p.notification elements across the page need #080840 as its color
- p.news elements across the page need #084008 as its color
Given this HTML:
<div id="container">
<p class="notification">
Some text in div#container p.notification
</p>
<p class="news">Some text in div#container .news</p>
<p>Some text in div#container p</p>
</div>
<p class="notification">Some text in p.notification</p>
<p class="news">Some text in .news</p>
And this CSS:
div#container p { color: #7d6a7e; }
p.notification { color: #080840 !important; }
p.news { color: #084008; }
You will see that the the div#container p.news element will NOT get #084008 as it's color.
Fix it by adding !important to the style like the notification.
Written by Alexander Brevig
Related protips
7 Responses
Another reason why you should never use IDs in styling.
@sheerun actually, I just tried to change the id to a class http://codepen.io/anon/pen/Afvto and it's still not displaying the p.news as one might think.
That's because of another CSS silly behavior. The order of rules matters less than number of elements in selector. If you wrote '.container p' then everything would be OK, because it contains one tag selector and one class selector, as well as 'p.notification ', so the order now matters.
You can use SCSS to avoid such problems (although compiled CSS will be much bigger).
Why not just set the color on the parent container?
See: http://codepen.io/ndorfin/pen/mdFyp
Just as a disclaimer, this is not intended as an example of how to write CSS, but rather what !important can be used for. I've found it to be a time saver many times in real-world situations where I don't have the time or access to refactor the CSS styles. The html and css are written the way they are to cause the problem that may arise when elements inherit styles from many selectors.
Most things are not !important.
Recommended reading: http://coding.smashingmagazine.com/2010/11/02/the-important-css-declaration-how-and-when-to-use-it/
In general, I try to minimize !important
use to general states only, e.g. .hidden
which should override normal rules.
"Another reason why you should never use IDs in styling."
This ist not really correct. Take a look at this article http://css-tricks.com/efficiently-rendering-css/ --> ID's are the most efficient, Universal are the least.