CSS Priorities and Feature Orientation

My question should be pretty solid. For some reason, I can’t hug my head around me today.

I create a menu with a structure like this

<div class="wrapper"> <ul> <li class="menu-item"><a href="#">Menu Item</a> <div class="inner"> <a href="#">Login</a> </div> </li> </ul> </div> 

I am trying to target a login link using the following css selector:

 .inner a{} 

The selector works, however the following selector accepts css presidence and overrides the above selector:

 li.menu-item a{} 

I am completely baffled. Why does the second selector prefer style over the first? How do you guys recommend me aiming at the above "a" elements?

+4
source share
5 answers

Why does the second selector prefer style over the first?

Since the second selector is more specific than the first. The first contains the class one and one , and the second one and two .

To calculate specificity, think of the selector as four numbers, all starting with (0,0,0,0)

  • Built-in styles have the highest specificity and replace the first number (1,0,0,0) .
  • The identifier is considered the second number (0,1,0,0)
  • The pseudo-classes ( except :not() ) and attribute selector classes are considered the third number (0,0,1,0)
  • Type selectors and pseudo-elements - for example. div {} or ::after{} count as fourth (0,0,0,1)

Also:

+10
source

CSS selectors have a weight system attached to them,

  • Element, pseudo-element: d = 1 - (0,0,0,1)
  • Class, pseudo-class, attribute: c = 1 - (0,0,1,0)
  • Id: b = 1 - (0,1,0,0)
  • Inline Style: a = 1 - (1,0,0,0)

therefore, your first selector has a rating of (0,0,1,1) while your second selector has a rating of (0,0,1,2) which is higher and therefore takes precedence

+2
source

This is because li.menu a contains three parts for the idendtify element: the parent element (li), the parent class (menu item) and element (a). Your intended selector has only two, so you can change it to this:

 li.inner a{} 

And it should work.

Edit:

I knew I answered this before: Why doesn't my HTML use the latest style defined in CSS?

+1
source

CSS priority wins the DOM object with the highest specificity.

So what deserves the specifics?

 Element Selector -- 1 Class Selector -- 10 ID Selector -- 100 Inline Selector -- 1000 

In your example: .inner a will be 11 points

 a(1) + .inner(10) = 11 

li.menu-item a - 12 points

 li(1) + .menu-item(10) + a(1) = 12 

So why the second will be shown. To make the style right, just make it more specific, for example use .menu-item.inner a

There is a very good article about this. http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

0
source

You can only apply CSS to the anchors inside each element, for example:

 li.menu-item > a{} .inner > a 

By doing this, the rules "li.menu-item a" will not interfere in another anchor.

0
source

Source: https://habr.com/ru/post/1479778/


All Articles