我对nth-of-type伪类有点困惑,以及它应该如何工作 - 特别是与nth-child类相比.
也许我有错误的想法,但鉴于这种结构
<div class="row">
<div class="icon">A</div>
<div class="icon">B</div>
<div class="label">1</div>
<div class="label">2</div>
<div class="label">3</div>
</div>
Run Code Online (Sandbox Code Playgroud)
..第三个子元素(第一个带有类标签)应该(也许?)可以选择
.row .label:nth-of-type(1) {
/* some rules */
}
Run Code Online (Sandbox Code Playgroud)
但是,至少在Chrome中,它不会选择它.只有当它是行中的第一个子节点时才会起作用,它与nth-child相同 - 因此,这与nth-of-type有什么区别?
Mad*_*iha 34
该nth-child
伪类指的是"第N个匹配的子元素",如果你有一个结构如下含义:
<div>
<h1>Hello</h1>
<p>Paragraph</p>
<p>Target</p>
</div>
Run Code Online (Sandbox Code Playgroud)
然后p:nth-child(2)
将选择也是ap的第二个孩子(即p
带有"段落").
p:nth-of-type
将选择第二个匹配的p
元素(即我们的目标p
).
这是Chris Coyier @ CSS-Tricks.com关于这个主题的精彩文章
你的中断的原因是因为type引用了元素的类型(即,div
),但第一个div与你提到的规则(.row .label
)不匹配,因此规则不适用.
其原因是,CSS解析从右到左,这意味着在浏览器首先查找上:nth-of-type(1)
,确定它搜索类型的元素div
,这也是第一个其类型,该匹配的.row
元件,以及第一,.icon
元件.然后它会读取该元素应该具有的.label
类,它与上面的内容不匹配.
如果要选择第一个标签元素,则需要将所有标签包装在自己的容器中,或者只是使用nth-of-type(3)
(假设总有2个图标).
另一个选择,(遗憾地)是使用...等待它... jQuery:
$(function () {
$('.row .label:first')
.css({
backgroundColor:"blue"
});
});
Run Code Online (Sandbox Code Playgroud)
.label:nth-of-type(1)
Run Code Online (Sandbox Code Playgroud)
"type"在这里指的是元素的类型.在这种情况下,div
不要上课.这并不意味着第一个元素.label
,它意味着它的类型的第一个元素,它也有一个类label
.
没有一类具有类型label
索引1
的元素.
在图片中添加了10个元素,8个是<p>
2个<i>
,两个阴影部分元素表示<i>
剩下的8个元素<p>
页面的CSS到这里:
<style>
* {
padding: 0;
margin:0;
}
section p {
width: 20px;
height: 20px;
border:solid 1px black;
border-radius: 15px;
margin:20px;
float: left;
}
section i {
width: 20px;
height: 20px;
border:solid 1px black;
border-radius: 15px;
margin:20px;
float: left;
}
section p:nth-child(1) {
background-color: green; /*first-child of p in the flow*/
}
section i:nth-child(1) {
background-color: red; /*[first-child of i in the flow]NO */
}
section i:nth-of-type(1) {
background-color: blue; /*the type i of first child in the flow*/
}
</style>
</head>
<body>
<section>
<p></p>
<p></p>
<p></p>
<p></p>
<i></i>
<p></p>
<i></i>
<p></p>
<p></p>
<p></p>
</section>
</body>
Run Code Online (Sandbox Code Playgroud)
第一个绿色灯泡表示
section p:nth-child(1) {
background-color: green; /*first-child of p in the flow*/
}
Run Code Online (Sandbox Code Playgroud)
代码中的第二个红色灯泡不起作用,因为我不是流程中的第一个元素
section i:nth-child(1) {
background-color: red; /*[first-child of i in the flow]NO */
}
Run Code Online (Sandbox Code Playgroud)
并且图中的蓝色灯泡表示流程中的第一种类型
section i:nth-of-type(1) {
background-color: blue; /*the type i of first child in the flow*/
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13673 次 |
最近记录: |