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 td
s 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.
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, class
es 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.
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:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With