Last Updated: February 25, 2016
·
1.094K
· alexanderbrevig

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.

http://codepen.io/anon/pen/vqEmB

7 Responses
Add your response

Another reason why you should never use IDs in styling.

over 1 year ago ·

@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.

over 1 year ago ·

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).

over 1 year ago ·

Why not just set the color on the parent container?
See: http://codepen.io/ndorfin/pen/mdFyp

over 1 year ago ·

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.

over 1 year ago ·

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.

over 1 year ago ·

@sheerun

"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.

over 1 year ago ·