F :first-child
选择F的第一个子元素(所有第一个子元素都会被选择)
<body>
<div id="container">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<div><p>我是div里面的第一个p</p></div>
<ul>
<li>我是ul中的第1个li</li>
<li>我是ul中的第2个li</li>
<li>我是ul中的第3个li</li>
<li>我是ul中的第4个li</li>
</ul>
</div>
</body>
<style>
#container :first-child{
color: pink;
}
</style>
效果如下:
注意“:”与前面的F中间要有一个空格,否则他会选择父元素中的所有子元素
F E:first-child
<style>
#container p:first-child{
color: pink;
}
</style>
实现效果如下:
在这里如果在p1前面再加上一个span元素,那个p1将不会变粉
E:first-child
选择作为第一个子元素的E元素,这里“:”前面没有空格
<style>
li:first-child{
color: pink;
}
</style>
实现效果如下:
F :last-child
具体实现类比F :first-child
:nth-child(n)
用来定位某父元素的一个或多个特定的子元素。其中“n”是参数,可以是整数值(1,2,3,4),也可以是表达式(2n+1、-n+5)和关键词(odd、even),参数n的起始值始终是1。也就是说,参数n的值为0时,选择器将选择不到任何匹配的元素。
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6</li>
</ul>
<style>
li:nth-child(2n+1){
background-color: pink;
}
</style>
实现效果如下:
:nth-last-child(n)
选择在其父元素中倒数第n个位置的元素或特定某元素。
具体使用与 :nth-child(n)类似
:first-of-type
选择器类似于“:first-child”选择器,不同之处就是指定了元素的类型,其主要用来定位一个父元素下的某个类型的第一个子元素。
<body>
<span>我是span</span>
<ul>
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
<p>我是第一个p</p>
<p>我是第二个p</p>
</body>
<style>
p:first-of-type{
background-color: pink;
}
</style>
实现如下:
:last-of-type
选择器和“:first-of-type”选择器功能是一样的,不同的是他选择是父元素下的某个类型的最后一个子元素。
:nth-of-type(n)
它只计算父元素中指定的某种类型的子元素[即E:nth-of-type(n)]。当某个元素中的子元素不单是同一种类型的子元素时,使用“:nth-of-type(n)”选择器来定位于父元素中某种类型的子元素是非常方便和有用的。在“:nth-of-type(n)”选择器中的“n”和“:nth-child(n)”选择器中的“n”参数也一样,可以是具体的整数,也可以是表达式,还可以是关键词。
原文链接:https://blog.csdn.net/Panda_m/article/details/50084699
<body>
<li>我是外边的第一个li</li>
<li>我是外边的第二个li</li>
<span>我是span</span>
<ul>
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
<p>我是第一个p</p>
<p>我是第二个p</p>
</body>
<style>
li:nth-of-type(2){
background-color: pink;
}
</style>
实现如下:
:nth-last-of-type(n)
选择器和“:nth-of-type(n)”选择器是一样的,选择父元素中指定的某种子元素类型,但它的起始方向是从最后一个子元素开始