结构伪类选择器:
总结--当页面上的某个元素处于在不同的位置上的时候,我们可以通过伪类选择器去选择某个标签或者某个class相同的元素
1.:nth-child(n) , :frist-child和:last-child
li:first-child 就是第一个li
li:last-child 就是最后一个li
li:nth-child(n) ,n是几就是第几个li
代码:
<style>
/* 选择父元素ul里面的li */
/* 选择ul里面的第一个孩 li */
ul li:first-child {
color: red;
}
/* 选择ul里面最后一个孩 li */
ul li:last-child {
color: aqua;
}
/* 选择ul里面第五个孩 li */
ul li:nth-child(5) {
color: aquamarine;
}
</style>
</head>
<body>
<ul>
<li>第一个孩</li>
<li>第二个孩</li>
<li>第三个孩</li>
<li>第四个孩</li>
<li>第五个孩</li>
<li>第六个孩</li>
<li>第七个孩</li>
</ul>
</body>
效果图:
1.1 :nth-child(odd)和:nth-child(even)
li:nth-child(odd) 就是排在奇数的li
li:nth-child(even) 就是排在偶数数的li
代码:
<style>
/* 选择父元素ul里面的li */
/* 选择ul里面奇数的孩 li */
ul li:nth-child(odd) {
color: pink;
}
/* 选择ul里面偶数的孩 li */
ul li:nth-child(even) {
color: aquamarine;
}
</style>
</head>
<body>
<ul>
<li>第一个孩</li>
<li>第二个孩</li>
<li>第三个孩</li>
<li>第四个孩</li>
<li>第五个孩</li>
<li>第六个孩</li>
<li>第七个孩</li>
</ul>
</body>
效果图:
1. li:nth-child(2n/3n/4n)
:2n是指第0、2、4、6、8等个li。3n是指第0、3、6、9、12等个li。4n是指第0、4、8、12、16等个li。
2.li:nth-child(even/odd/3n/n)
:从第一个li开始数的。
3.li:nth-last-child(even/odd/3n/n)
:从最后一个li开始数的。
2.:first-of-type和:last-of-type
代码:
<style>
/* 第一个兄弟p */
p:first-of-type {
color: red;
font-size: 18px;
}
/* 最后一个兄弟p */
p:last-of-type {
color: green;
font-size: 18px;
}
</style>
</head>
<body>
<h1>我是干嘛的</h1>
<p>孙悟空</p>
<p>猪八戒</p>
<p>沙和尚</p>
</body>
效果图:
注:nth-child与nth-of-type区别:
1. nth-child 对父元素里面所有孩子排序选择(序号是固定的)先找到第n个孩子,然后看看是否和p匹配,若不匹配则不使用
2. nth-of-type 对父元素里面指定子元素进行排序选择。先去匹配p . 然后再根据p找第n个孩子