<div>
<h1>我是标题1</h1>
<span>span1</span>
<span>span2</span>
<span>span3</span>
<span>span4</span>
<h1>我是标题1</h1>
</div>
div span {
background: lightgreen;
}
div span:first-child {
background: red;
}
div span:last-child {
background: orange;
}
image
使用以上代码,希望对div下的第一个span和最后一个span进行更改背景色,发现无效果,
将前后的<h1>我是标题1</h1>
去掉后才正常显示
在W3school上的描述是
image重点是和父元素有关系,即元素是对应的选择器且为父元素的第一个子元素,才会应用选择器对应的样式。
为了提高代码的可读性,减少伪类表意和真实作用的混淆,first-child这类伪类选择器建议只在同一特征的元素上使用。
网友评论