Samuel
Samuel

Reputation: 18586

CSS rule not being overridden

I ran into a weird issue, where a CSS rule doesn't seem to be applied correctly on Safari/Chrome/Firefox on Mac.

Given the following html code:

<table id="table" border="1">
    <tr>
        <td id="cell">
            Hello
        </td>
    </tr>
</table>

Then the following css code works as I expected (as in the cell doesn't have padding on top):

td { padding: 10px; }
#cell { padding-top: 0px; }

But this one doesn't:

#table td { padding: 10px; }
#cell { padding-top: 0px; }

(Try it out online at: http://jsfiddle.net/xkduyk7m/)

I expected both versions of the CSS to yield the same effect in this case, but in the second case the rule that is added later and that applies to the specific cell doesn't override the first rule.

Why?

Upvotes: 2

Views: 719

Answers (3)

Evan
Evan

Reputation: 5

Your problem is that the #table td { padding:10px; } will wright out as #table td { padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; } by the browser. And this priority over your #cell { padding-top:0px; } . try one of the fallowing 2 options

Option 1

#table td { padding: 10px 10px 10px 10px; }
#table #cell { padding: 0px 10px 10px 10px; }

Option 2

#table td { padding: 10px; }
#table #cell { padding-top: 0px !important; }

Sorry for the bolding using stack overflow android app and the hash makes it bold sorry for that

Upvotes: 0

LcSalazar
LcSalazar

Reputation: 16821

Each css selector has a value "weight". The combination makes it override one another, and when they match, the order of writing will define the precedence.

Here are W3's docs about how to calculate the precedence: http://www.w3.org/TR/CSS2/cascade.html#specificity

Upvotes: 4

Mathieu David
Mathieu David

Reputation: 5278

Css rules are not place bound. A more specific css selector will override another less specific. Place is only used in case they are both as specific.

In your case #table td is more specific than just #cell and thus is not being overridden. If you use #table #cell it should work

Upvotes: 2

Related Questions