Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS priorities and targeting specific elements

My question should be pretty strait forward. For some reason I can't wrap my head around it today.

I'm making a menu with a structure like so

<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 the login link using the following css selector:

.inner a{}

The selector is working, however the following selector is taking css presidence, and overriding the above selector:

li.menu-item a{}

I'm totally baffled. Why would the second selector take style preference over the first? How would you guys recommend I target the above "a" elements?

like image 780
Alex Ritter Avatar asked Dec 07 '22 07:12

Alex Ritter


1 Answers

Why would the second selector take style preference over the first?

Because the second selector is more specific than the first. The first contains one class and one type selector while the second has one class and two type selectors.

To calculate specificity, think of an selector as consiting of four numbers, all starting at (0,0,0,0)

  • Inline styles have the highest specificity and would take the place of the first number (1,0,0,0).
  • ID's count as the second number (0,1,0,0)
  • Classes, pseudo-classes (other than :not()) and attribute selectors count as the third number (0,0,1,0)
  • Type selectors and pseudo-elements - e.g. div {} or ::after{} count as the fourth (0,0,0,1)

Also:

  • The universal selector * has no effect on a selectors specificity.
  • Combinators like +, ~ and > also have no effect on specificity.
  • !important rules almost always take precedence; though they don't affect the four numbers associated with a selectors specificity. Only another !important rule can override a previously defined one. The exception is when the previously defined !important rule has a more specific selector. Here, the normal rule of specificity (described above) apply.
like image 57
17 revs Avatar answered Jan 01 '23 05:01

17 revs