RMT
RMT

Reputation: 1162

Highest priority of CSS styles

I want to make a CSS style that takes more priority than another.

The css rule I want to have higher priority of is #an-id *. This is a CSS selector that selects all the elements underneath. And I have a class on an element underneath this, e.g. .my-class-name, and this will not get prioritized. Will this work: #an-id * .my-class-name? Or should I just do this: #an-id .my-class-name?

Upvotes: 2

Views: 1353

Answers (2)

Axel Köhler
Axel Köhler

Reputation: 1015

Read this article on CSS specifity: https://css-tricks.com/specifics-on-css-specificity/

For each class value (or pseudo-class or attribute selector), apply 0,0,1,0 points

The universal selector (*) has no specificity value (0,0,0,0)

Your example #an-id * .my-class-name is wrong, because it would target all .my-class-name elements within each element that is within #an-id (so at least two levels down), but actually your .my-class-name element is one level below #an-id. To fix this, just use #an-id .my-class-name (without the asterix).

Since #an-id .my-class-name has a score of 0,1,1,0 and #an-id * has a score of 0,1,0,1, this will overwrite your #an-id * style rule.

See this example.

Upvotes: 1

Wimanicesir
Wimanicesir

Reputation: 5122

The two options you give are not targeting the same.

#an-id * .my-class-name

Will give you all child elements of an-id that have a child named ".my-class-name"

#an-id .my-class-name

Will give you all child elements with class named ".my-class-name"

So

<div id="an-id"><div class=".my-class-name">test</div></div>

This will not be styled in the first rule but will be styled with the second one.

Also, I would strongly recommend using SASS/SCSS. This makes it way easier!

Upvotes: 2

Related Questions