问题描述
我的问题应该很短暂。因为某种原因,今天我不能绕过头。
我正在做一个结构像这样的菜单
< 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>伪类()和计数为第三个数字(0, 0,1,0)
- 和伪元素 - 例如
div {}
或:: after {}
计为第四个(0,0,0,1 )
另外:
-
*
对选择器特异性没有影响。 - 喜欢
+
,〜
和> / code>对特异性没有影响。
- 规则几乎总是优先;尽管它们不影响与选择子特异性相关的四个数字。只有另一个
!important
规则可以覆盖先前定义的规则。 这里,正常的特异性规则(如上所述)适用。
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?
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.
这篇关于CSS优先级和定位特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!