March 31, 2012

Overriding styles without !important

Question by Hendrik

How is it possible to override styles specified in another style sheet?

I do not want to use the !important tag to override them. I would much rather specify a new style sheet, put styles in there. Could this be achieved by changing the load order of the style sheets?

Answer by minitech

It depends. CSS stands for Cascading Style Sheets, and there’s a specific order that styles are applied in, overwriting previous styles. Without going into too much detail:

  • If your rules have the same specificity, just load your stylesheet second and everything will work fine.
  • If your rules have higher specificity, the order won’t matter.
  • If your rules have lower specificity, you’ll need to modify them to match.

So, what’s specificity? Basically, it’s the sum of each selector in a rule. So this:

a {
    background-color: black;
    color: white;
}

Has less specificity than this:

body a {
    color: orange;
}

. ID selectors have higher specificity than class selectors, which have the same specificity as pseudo-class selectors, which have higher specificity than tag selectors. So if all your content is contained in a <div> with an id of content, you would be able to override a style that looks like this:

body a {
    border: 0;
}

With:

#content a {
    border: 1px solid black;
}

Answer by Starx

If you can increase the specificity of styles, you can do this without the !important.

For example:

HTML

<div id="selector">
  <a>Hello</a>
  <a class="specific">Hi</a>
</div>

CSS

div a {}

Will be ignored, if you give a specific class inside #selector

.specific { }

Here is a demo explaining my point. Basically, the idea is to define the styles as closely as possible.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!