WClarke
WClarke

Reputation: 101

CSS attribute selectors taking precedence over normal CSS class selectors

I originally noticed this problem when working with CSS in an SVG file, and thought it was rendering error, but after trying it in HTML, the same situation occurred.

Take the following code:

.example {color:green}
.example {color:blue}

In this case, as expected using normal class selectors, the value of color is initially green, though later in the file it is redefined as blue, thus the resulting color of elements in the class are blue.

Now take this example:

div[class='example'] {color:green}
.example {color:blue}

In this case, now initially defining the color value for divs in example using attribute selectors, when the value is redefined using normal CSS class selectors, the change from green to blue is ignored in the divs, and the value set by the attribute selector takes precedence, despite the blue color value for the whole class being redeclared later in the file.

According to Mozilla documentation on CSS class selectors, it says normal selectors and attribute selectors are "equivalent", though that doesn't appear to be the case in this situation. What is the cause of this?

Upvotes: 0

Views: 524

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

I'd originally posted this as a comment, but perhaps I should've made it answer.


Let's look at the actual conditions of your two CSS rules:

div[class='example'] {color:green}
  • Element must be a <div>
  • Element must have class "example"
.example {color:blue}
  • Element must have class "example"

Because your first CSS rule has two conditions, whereas your second rule only has one, the first rule is more specific - therefore it will take precedence.

If you were to remove the div portion from your first rule, it would be considered equivalent (as MDN states), at which point the text would be blue.

Upvotes: 2

Mario Petrovic
Mario Petrovic

Reputation: 8312

Mozilla documentation is correct. But when considering specificity, you need to take in to the account div and [class='example']. These two combined are stronger than .example.

Here is an nice representation of specificity: https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/

If you go and open smasingmagazine.com articele, you will conclude that:

.example has power of 10

Whereas div[class='example'] has power of 11

Upvotes: 0

Related Questions