美文网首页
2020-02-14 CSS伪类:first-child踩坑记录

2020-02-14 CSS伪类:first-child踩坑记录

作者: __唐一__ | 来源:发表于2020-02-14 17:12 被阅读0次
<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>去掉后才正常显示

image-20200214160258444

在W3school上的描述是

image

重点是和父元素有关系,即元素是对应的选择器且为父元素的第一个子元素,才会应用选择器对应的样式。

为了提高代码的可读性,减少伪类表意和真实作用的混淆,first-child这类伪类选择器建议只在同一特征的元素上使用。

相关文章

网友评论

      本文标题:2020-02-14 CSS伪类:first-child踩坑记录

      本文链接:https://www.haomeiwen.com/subject/ztrjfhtx.html