闻心阁

一蓑烟雨看苍生,半壶浊酒笑红尘

CSS3 first-child not work

2017-01-20 约 1 分钟读完 搬砖秘籍

For some reason, I tried to use CSS3 selector :first-child, but it not works in my project.

the CSS code:

<style>
  p {
    font-size: 15px;
    color: #888888;
  }
  p:first-child{
    font-size: 30px;
    color: red;
  }
</style>

the HTML code

<div class="box">
  <div class="text">
    some text
  </div>
  <div class="text">
    some text one
  </div>
  <p>text one</p>
  <p>text two</p>
</div>

I think the first p tag would be changed, but it’s not.

Why it not work?

When the first-child selector is used, it would find the parent node first(and here the parent node is box), and then find the first child of the box. But the first child of box is div not p, so the page shows first-child not work.

Solution

The solution is easy, just add the only parent node out of the p tag. just like this

<div class="box">
  <div class="text">
    some text
  </div>
  <div class="text">
    some text one
  </div>
  <div>
    <p>text one</p>
    <p>text two</p>
  </div>
</div>

and then it works:-)