CSS Universal selector (*) specificity
Asked Answered
M

2

6

I'm trying to figure out why .x has higher specificity than *.x when the latter is expected to win.

Isn't *.x supposed to have a specificty of 0-0-1-1 (1 class, 1 tag) while .x is just a single class 0-0-1-0?

Consider the following basic code:

*.x { color: blue; }

.x { color: red }
<p class="x">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque, nam.</p>

It should be blue. To demonstrate an expected behaviour, I replaced * with another element (p):

p.x { color: blue; }

.x { color: red }
<p class="x">This time it works.</p>
Masseuse answered 15/4, 2016 at 9:41 Comment(1)
The universal selector has a specificity of 0, 0, 0, 0 You can't see the * as a tag. In your case, both are equal ...Barthol
T
7

The universal selector (*) has no effect on specifity, therefore the latter selector's styles will be the ones that are applied.

An asterisk (*) is the universal selector for CSS. It matches a single element of any type. Omitting the asterisk with simple selectors has the same effect. For instance, *.warning and .warning are considered equal.

Titrant answered 15/4, 2016 at 9:45 Comment(1)
I'm not following this. When I make a rule for *, it appears to take priority over all my other tag and class rules. I want it to contain default values for all elements, so I want it to have low priority!Patella
O
2

This is to be expected. The W3C spec says,

" A selector’s specificity is calculated for a given element as follows:

  • count the number of ID selectors in the selector (= A)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= B)
  • count the number of type selectors and pseudo-elements in the selector (= C)
  • ignore the universal selector

"

Note the last bullet.

Reference: https://www.w3.org/TR/selectors/#specificity

Overstride answered 14/5, 2019 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.