CSS优先级和定位特定元素 [英] CSS priorities and targeting specific elements

查看:136
本文介绍了CSS优先级和定位特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题应该很短暂。因为某种原因,今天我不能绕过头。



我正在做一个结构像这样的菜单

 < div class =wrapper> 
< ul>
< li class =menu-item>< a href =#>菜单项< / a>
< div class =inner>
< a href =#>登录< / a>
< / div>
< / li>
< / ul>
< / div>

我尝试使用以下css选择器来定位登录链接:

  .inner a {} 

选择器正在工作,但以下选择器正在采取css先决条件,并覆盖上述选择器:

  li.menu a {} 

我完全感到困惑。为什么第二个选择器的样式偏好超过第一个?

解决方案


为什么第二个选择器优先于第一个?


因为第二个选择器更多具体比第一个。第一个包含一个类型选择器,而第二个包含一个类别和两个类型选择器。



要计算特异性,可以将选择器视为四个数字的联合,所有数字都始于(0,0,0,0) p>


  • 内联样式具有最高的特异性,并替换第一个数字(1,0,0,0)

  • ID

  • ID
  • href =http://www.w3.org/TR/css3-selectors/#pseudo-classes =nofollow>伪类( :not() )和属性选择器计数为第三个数字(0, 0,1,0)
  • 类型选择器和伪元素 - 例如 div {} :: after {} 计为第四个(0,0,0,1 )



另外:




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?

解决方案

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:

这篇关于CSS优先级和定位特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆