CSS-Selektor: Ruft das erste Element mit der angegebenen Klasse ab
P粉170438285
P粉170438285 2024-03-25 15:49:20
0
2
637

Ich habe eine Reihe erster Elemente mit dem Klassennamen red 的元素,但我似乎无法使用以下 CSS 规则选择带有 class="red":

.home .red:first-child {
    border: 1px solid red;
}
<div class="home">
    <span>blah</span>
    <p class="red">first</p>
    <p class="red">second</p>
    <p class="red">third</p>
    <p class="red">fourth</p>
</div>

Was stimmt mit dieser Auswahl nicht und wie kann ich sie korrigieren, um das erste Kind mit der red-Klasse anzusprechen?

P粉170438285
P粉170438285

Antworte allen(2)
P粉131455722

:first-child 选择器的目的是,如名称所示,选择父标记的第一个子标记。所以这个例子是可行的(刚刚在这里尝试过):

    

first

second

但是,如果您将标签嵌套在不同的父标签下,或者您的 red 类标签不是父标签下的第一个标签,则此方法不起作用。

还请注意,这不仅适用于整个文档中的第一个此类标记,而且每次都有新的父级标记围绕它时,例如:

first

second

third

fourth

firstthird 将为红色。

对于您的情况,您可以使用 :nth-of-type 选择器:

.red:nth-of-type(1)
{
    border:5px solid red;
} 
blah

first

second

third

fourth

感谢 Martyn,他删除了包含此方法的答案。

有关 :nth-child():nth-of-type() 的更多信息,请访问 http://www.quirksmode.org/css/nthchild.html

请注意,这是一个 CSS3 选择器,因此一些现在过时的浏览器版本可能无法按预期运行(例如 IE8 或更早版本)。访问 https://caniuse.com/?search=nth-of-type更多详细信息。

P粉996763314

这是作者误解 :first-child 如何工作的最著名的例子之一。 CSS2中引入:first-child伪类代表其父母的第一个孩子。就是这样。有一个非常常见的误解,即它会选择第一个与复合选择器其余部分指定的条件相匹配的子元素。由于选择器的工作方式(请参阅这里 进行解释),这根本不是真的。

选择器级别 3 引入了 :first-of- type 伪类,表示其元素类型的兄弟元素中的第一个元素。 这个答案图文并茂地解释了 :first-child:first-of-type 之间的区别。但是,与 :first-child 一样,它不会查看任何其他条件或属性。在 HTML 中,元素类型由标签名称表示。在问题中,该类型是 p

不幸的是,没有类似的 :first-of-class 伪类来匹配给定类的第一个子元素。在首次发布此答案时,新发布的 FPWD选择器级别 4 引入了 :nth-match() 伪类,它是围绕现有选择器机制设计的,正如我在第一段中提到的,通过添加选择器列表参数,您可以通过它提供其余的选择器复合选择器以获得所需的过滤行为。近年来,此功能纳入 :nth-child( ) 本身,选择器列表作为可选的第二个参数出现,以简化事情并避免 :nth-match() 在整个文档中匹配的错误印象(请参阅下面的最后注释) .

当我们等待跨浏览器支持时(说真的,已经过去近 10 年了,并且在过去 5 年中只有一个实现),这是一种解决方法 Lea Verou 和我独立开发(她先做的!)是首先将您想要的样式应用到该类的所有元素:

/* 
 * Select all .red children of .home, including the first one,
 * and give them a border.
 */
.home > .red {
    border: 1px solid red;
}

...然后使用覆盖规则中的通用同级组合器 ~

/* 
 * Select all but the first .red child of .home,
 * and remove the border from the previous rule.
 */
.home > .red ~ .red {
    border: none;
}

现在只有第一个带有 class="red" 的元素才会有边框。

以下是如何应用规则的说明:

.home > .red {
    border: 1px solid red;
}

.home > .red ~ .red {
    border: none;
}
blah

first

second

third

fourth

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!