nth-of-type不是指定类型,为什么用类选择器的时候,第一个选不出来
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>star</title>
<style>
.container {
position: relative;
width: 1200px;
height: 800px;
background-color: red;
}
.star {
position: absolute;
width: 0px;
height: 0px;
transform: rotate(35deg) translate(102%, 165%);
border-right: 100px solid transparent;
border-bottom: 70px solid yellow;
border-left: 100px solid transparent;
}
div.star::before {
position: absolute;
left: 0;
top: 0;
display: block;
content: ' ';
width: 0px;
height: 0px;
transform: rotate(75deg) translate(-15%, 129%);
border-right: 100px solid transparent;
border-bottom: 70px solid yellow;
border-left: 100px solid transparent;
}
div.star::after {
position: absolute;
left: 0;
top: 0;
display: block;
content: ' ';
width: 0px;
height: 0px;
transform: rotate(-70deg) translate(-17%, -134%);
border-right: 100px solid transparent;
border-bottom: 70px solid yellow;
border-left: 100px solid transparent;
}
.small {
transform: scale(0.3);
}
.small:nth-of-type(2) {
top: 20px;
left: 300px;
}
.small:nth-of-type(3) {
top: 100px;
left: 400px;
}
.small:nth-of-type(4) {
top: 220px;
left: 430px;
}
.small:nth-of-type(5) {
top: 350px;
left: 400px;
}
.small:nth-of-type(6) {
top: 400px;
left: 300px;
transform: rotate(40deg) scale(0.3);
}
</style>
</head>
<body>
<div class="container">
<div class="star"></div>
<div class="star small x"></div>
<div class="star small"></div>
<div class="star small"></div>
<div class="star small"></div>
<div class="star small"></div>
</div>
</body>
</html>请教老师, 如上方代码, 一共定义了五个small类, 但是 .small:nth-of-type(1)是定位不到任何元素的, 只能从2开始, 不是说nth-of-type是指定元素类型的么( 我理解的是仅计数small类的元素 ,然后从从父元素中第一个1small类的元素开始计数 ),这里怎么跟nth-child一样了, 第一个div( 只定义了star类的)被当做了第一个子元素. 谢谢
正在回答
你好,:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。但是这个同类型不是特指选择器类型,这块还与标签(元素)类型,有关系,可以结合以下例子来理解:
1、这里会被选中两个,因为不同类型(这里是由于标签类型不同)会被当作多类,只要符合选择器规范都会选中。即:如果是class那么碰到不同类型的,单独一类,符合条件的选中。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.red:nth-of-type(1) { color: red; }
</style>
</head>
<body>
<section>
<div class="red">我是一个普通的div标签</div>
<p class="red">我是第1个p标签</p>
<p class="red">我是第2个p标签</p>
</section>
</body>
</html>2、这里就是因为标签相同,但选择器不同了(就是代码中遇到的问题哦)。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box2:nth-of-type(2) {
background: #fed;
}
</style>
</head>
<body>
<div class="content">
<p class="box2">box2</p>
<p>text</p>
<p class="box2">box2</p>
</div>
</body>
</html>这里用的.box2并且还是按照类型来选择,但一开始它是不知道你要选择的元素类型的,当选中第一个时,它就会确认这个元素的类型,然后后面的选择根据这个类型来选,每碰到这个类型它就加1,如果你想选择的是第一个p应该写nth-of-type(1)第三个p应该写nth-of-type(3)。
祝学习愉快~
- 参与学习 人
- 提交作业 2198 份
- 解答问题 5012 个
如果你有web端基础,既想进阶,又想进军移动端开发,那就来吧,我们专题为你带来的课程有HTML5、CSS3、移动基础、响应式、bootstrap、less等,让你在前端道路上畅通无阻!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星