JW Lim
JW Lim

Reputation: 1814

Why does a descendant selector override a class selector?

I have classes like this:

.tableGeneric tr td
{
    text-align: center;
    vertical-align: middle;
    border: 1px solid black;
}
.tdValignTop
{
    vertical-align: top;
}

When I apply these classes, I expect that a td with class .tdValignTop would be vertically-aligned to the top, even when .tableGeneric tries to align it to the middle. However, it would seem that I am wrong: the table cell would use .tableGeneric's styles instead of .tdValignTop's styles.

Here's a fiddle to demonstrate.

So... why? Isn't a specific class style/selector supposed to override base/parent styles? Is there some kind of logic or reasoning behind this behavior? I assume the behavior is intentional, but I cannot find any documentation on it.

Upvotes: 0

Views: 321

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201618

What you think of as “specific” is not more specific in the CSS sense, and it is CSS specificity that matters when applying CSS. The CSS specificity rules define specificity on terms of the syntactic structure of a selector. In this case, the first selector has one class name and two element names, so it is more specific than the other, which only contains a class name.

Upvotes: 1

Rob Sobers
Rob Sobers

Reputation: 21135

This is because the first style rule you defined is more specific than the second, thus it will override.

If you do this it will work as you expect:

.tableGeneric tr td
{
    text-align: center;
    vertical-align: middle;
    border: 1px solid black;
}
.tableGeneric tr td.tdValignTop
{
    vertical-align: top;
}

Working example here.

Upvotes: 1

Related Questions