Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a CSS rule override another CSS rule?

Tags:

html

dom

css

So, this is what I'm doing:

#id-form td {
padding: 0 0 10px 0;
}

#particular-td {
border: 1px solid black;
text-align: center;
background-color: #DFDFDF;
height: 30px;
padding: 10px;
}

I have a table #id-form, on which I set all tds to have padding-bottom: 10px.
But on one special occasion, I want a particular td to have padding: 10px in all directions, which I set in the #particular-td.

Obviously, I put the CSS styling in sequence in an external file.
But the rendered CSS only has padding-bottom, and padding: 10px appears to be overridden!?

Please explain:
How and why is this happening?
How should I arrange these rules to solve my problem (other than inline styling)?

EDIT: I removed 'table' before #id-form in table. I was never using this, I just mentioned it here to be able to explain it better.

like image 542
Pulkit Mittal Avatar asked Oct 08 '12 11:10

Pulkit Mittal


2 Answers

Because of CSS Specificity. A selector's weighting is evaluated based on the components that make it up, with id's given a weighting of 100, classes with a weighting of 10, and element selectors with weighting of 1.

So in your example:

table#id-form td

Has a weighting of 102 (table#id is 101 and td is 1), whereas this:

#particular-td

Has a weighting of 100. If you change your second to this:

#id-form #particular-td

You will get a weighting of 200 which will override the previous selector. Only as a last resort should you ever use !important, as this pretty much prevents you from overriding it further down the line.

like image 192
chrisfrancis27 Avatar answered Sep 18 '22 02:09

chrisfrancis27


This has to do with specificity. table#id-form td is more specific than #particular-td. A rule with higher specificity has precedence over a rule with lower specificity.

Here are a few resources to get you started on understanding how it works:

  • Smashing Magazine article
  • W3C spec on specificity
  • Specificity calculator

About using !important, as suggested by others:

One might be tempted to use the !important keyword to sort this out, but that is rarely a good idea:

  1. It becomes a pain to maintain/troubleshoot
  2. It breaks the normal flow of CSS
  3. The rule cannot be overridden by other rules later on

It might take a few minutes to read up on specificity, but it will be well worth the time spent when you've got a grasp of it.

like image 40
Christofer Eliasson Avatar answered Sep 22 '22 02:09

Christofer Eliasson