gpt4 book ai didi

css - CSS 选择器规范冲突中的优先级(类型选择器与类选择器)

转载 作者:技术小花猫 更新时间:2023-10-29 11:14:48 25 4
gpt4 key购买 nike

我从这个 tutorial 中了解了选择器优先级.在一种情况下,我很难理解这种行为。我有一个 HTML 元素:

<input class="top_bar_login_form_input" type="text"  name="email" placeholder="Prijavno ime">

问题是来自另一个选择器的属性覆盖了类的属性。

Picture

如上图所示,该类被一个不太具体的选择器覆盖。元素由 input[type="text"] 选择,这没有类那么具体。我看到的这些行为背后的唯一原因是 .inputbox 类也在确定优先级时进行了计算,即使它与元素不匹配。

为什么类型选择器会覆盖类选择器?

最佳答案

TL;DR 答案

第一个规则比第二个规则更具体因为它同时具有选择器的类型和属性部分,因此具有优先级:

input[type="text"] { }         /* type + attribute for specificity */
.top_bar_login_form_input { } /* only class for specificity, so *less* specificity */

更长的答案

您会认为作为属性选择器的type="text" 位比类选择器更具体,符合the MDN page on specificity。 :

The following list of selectors is by increasing specificity:

  • Universal selectors
  • Type selectors
  • Class selectors
  • Attributes selectors
  • Pseudo-classes
  • ID selectors
  • Inline style

上面的引述是在撰写此答案时的 MDN 文章中。

为什么会产生误导:

(感谢@BoltClock 的 insights 。)

以上仅似乎是正确的,但那是因为您通常在执行属性选择器时将元素包含在选择器中(例如 input[type="text"]) .然而,偷偷摸摸的是:input 位很重要。

假设我们有以下标记:

<input class="my-class" type="text" value="some value" />

following scenario输入呈现红色:

[type="text"] { color: green; }
.my-class { color: red; } /* last rule matched */

如果我们颠倒a scenario中的规则,输入将呈现绿色:

.my-class { color: red; }
[type="text"] { color: green; } /* last rule matched */

这是因为两个选择器具有相同的特异性。现在将input选择器引入到属性规则中将使其中之一更加具体,可以在this scenario中看到。 :

input[type="text"] { color: green; }  /* most _specific_ rule matched */
.my-class { color: red; }

W3 spec让我头疼,但它确实详细说明了上述方法的工作原理。另见 the answer by @BoltClock以及这些代码示例中的注释,以获取有关如何计算特异性的信息。

关于css - CSS 选择器规范冲突中的优先级(类型选择器与类选择器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14666581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com