今天遇到first-child不起作用,在网上搜了一下,发现这篇文章,才发现以往对这个伪类的理解居然都是错误的,在此纠正一下

first-child是css3中的控制器,意味着选择统计元素的第一个元素

我们先看一个例子:
css代码:

<style>
.dm p:first-child { background:#09C;color:#fff}
.dm p:last-child { background:#09C;color:#fff}
</style>

html代码:

<div class="dm">
<span>第一行</span>
<p>第二行</p>
<p>第三行</p>
<p>第四行</p>
<p>第五行</p>
<span>最后一行</span>
</div>

结果是:

这里面的first-child与last-child没有起到任何的作用。

 

先不说原因,我们把html代码改一下:

<div class="dm">
<p>第一行</p>
<p>第二行</p>
<p>第三行</p>
<p>第四行</p>
<p>第五行</p>
<p>最后一行</p>
</div>

再看一下效果:

这次起作用了

 

第一个例子里的第一个标签和最后一个标签都是span,而我们寻找的first-child和last-child都是P,[如果父元素的第一个元素或者最后一个元素不是寻找的标签的话,会不起作用],这样说着有点拗口,按上面的例子来说如果父元素.dm寻找的first-child与last-child是P,如果不是P的话会不起作用,大家需要注意这一点。

 

相关文章:

  • 2022-12-23
  • 2021-10-07
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-15
猜你喜欢
  • 2022-12-23
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2021-08-12
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案