MeltingDog
MeltingDog

Reputation: 15458

CSS Styling not 'cascading'?

I am updating someones site. Their markup selecting <a> tags is like this:

#wrapper a{color: red;}

Which is fine. But if I create a <div> within wrapper and give it the <a> tags my own styling eg:

.mydiv a{color: white;}

It simply doesnt work - the color:white in my <div> gets overwritten by the color:red in wrapper, even though the .mydiv css is located below the #wrapper css on my external style sheet. Whats more every other styling - background-color, border, etc - works fine!

Upvotes: 5

Views: 2928

Answers (2)

Aaron
Aaron

Reputation: 5237

The reason your CSS rule is being overwritten is because the priority of style rules depends largely on the specificity at which they're defined.

.myClass a is less specific than #myID a, as class selection implies a broader range of elements to be affected by the rule than does ID. To ensure that your rule takes precedence over the old one, simply use #wrapper .mydiv a as your selector, thereby enhancing the specificity of your rule to surpass that of the old one.

Upvotes: 0

Blender
Blender

Reputation: 298344

This is called specificity.

The selector with the id attribute is more specific than the selector with the class attribute (the former points to a single element but the latter points to multiple elements), so the selector with the id takes precedence over yours regardless of the order.

Your selector needs to be more specific in order to override the other selector:

#wrapper .mydiv a{color: white;}

Upvotes: 14

Related Questions