CSS中first-child和nth-child的讲解
2017-11-28 15:58
597 查看
first-child
E:first-child是伪类选择器,很多人都知道它的存在,但是在使用时,可以仍存在误解。
说明
匹配父元素的第一个子元素E从说明可以看出E是你要选择的第一个子元素,而不是父元素。一开始,误以为
E:first-child是E的第一个子元素。
举个例子:
<ul> <li>l1</li> <li>l2</li> <li>l3</li> </ul>1
2
3
4
5
假设选择的是第一个
li元素,则选择器应为
li:first-child,而不是
ul:first-child
<div> <h1>h1</h1> <p>p1</p> <p>p2</p> <p>p3</p> </div>1
2
3
4
5
6
这时选择第一个
p元素,应用
p:first-child则会出现错误,因为p的父元素是div,而对于div来说,它的第一个子元素不是p,而是h1,所以如果选择器
p:first-child,则会出错。
同理,
E:last-child``E:only-child与上面的一样,E元素必须是其父元素的最后一个子元素或唯一一个子元素才可以。
:nth-child(n)
说明
匹配父元素的第n个子元素EE也是子元素,而且也只能匹配父元素下第n个子元素。n是从1开始计数
<div> <h1>h1</h1> <p>p1</p> <p>p2</p> <p>p3</p> </div>1
2
3
4
5
6
依然是上面的例子,如果这次要选择第一个p元素,则可以使用
p:nth-child(2),因为第一个p元素在父元素
<div>下是第二个子元素,所以n需要取值为2。
所以要记住:
E:nth-child(n)中,E是你要选择的子元素,而n是E元素的父元素下,E元素所处的顺序数。
后记
此博文就是在练习时候发现关于css选择器方面理解不够深刻时,理解练习后所写的。所以关于css的选择器不能只停留在懂,还得多练。
相关文章推荐
- CSS中first-child和nth-child的讲解
- CSS选取第几个标签元素:nth-child、first-child、last-child
- CSS选取第几个标签元素:nth-child(n)、first-child、last-child
- CSS中的第一个:first-letter 最后一个:last-child 第n个:nth-child 伪元素
- CSS nth-child、first-child、last-child、nth-of-type、first-of-type和last-of-type选择器使用
- css中的first-child nth-child nth-last-child() 和:nth-of-type(n)
- CSS nth-child、first-child、last-child、nth-of-type、first-of-type和last-of-type选择器使用
- CSS选取第几个标签元素:nth-child、first-child、last-child
- [CSS] DOM Hierarchy Pseudo Classes :first-child :last-child :nth-child (demystified)
- css:first-child、last-child、nth-child、 nth-last-child
- 让IE7/8使用CSS中first-child和last-child样式属性
- CSS3中first-child、last-child、nth-child、nth-last-child
- CSS中:nth-child和JQuery:eq的区别
- CSS :first-child 选择器
- CSS3伪类选择器:nth-child()
- css表格各行颜色交替 tr:nth-child(odd)
- css nth-child和nth-type-of 区别
- CSS:nth-child
- :nth-last-child() | CSS属性参考
- 详解CSS中:nth-child的用法