CSS override rules and specificity
09:28 29 Jun 2012

I'm often confused by CSS override rules: in general, I realize that more specific style-sheets override less specific ones, and that specificity is determined by how many selectors are specified. There's also the !important keyword, which plays a role as well.

So, here's a simple example: I have a table with two table cells. The table itself has a CSS rule which applies to all cells within the table. However, the second table cell has its own rule which should override the general table rule:







    
abc
abc

But... when I open this in a browser, I see that rule2 doesn't override rule1. Okay - so I guess I need to make rule2 more "specific", but I can't really define any further selectors since I just want to apply it to a particular table cell. I tried adding the ! important keyword, but that doesn't work either.

I'm able to override rule2 if I wrap the text node in a

, like:

abc

...and then make the CSS rule more specific:

td.rule2 div {
    background-color: #ffff00; !important
}

This works, but it's not exactly what I want. For one thing, I want to apply the rule to the table cell, not the div. It makes a difference because you can still see the background color of rule1 as a border around the div.

What do I need to do to tell CSS I want rule2 to override rule1 for the td element?

html css