:first-child无法选择第一个h4元素

2 html css css-selectors

我想知道我为什么不能缩进:first-childh4.

其余所有h4元素都不应缩进.

HTML:

<section>
    <article id="5">
        <h2>Top 7 Best Pheromone Colognes for Men (To Attract Women)</h2>
        <h3>2014-01-16</h3>

        <!--img src="https://puaction.com/img/thumb/pua-berlin.jpg" width=80 height=80 title="" alt="" -->

        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>
        <h4>What Are Pheromones And Pheromone Colognes? Naturally, pheromones are odorless substances being excreted externally by the fertile body...</h4>

    </article>
</section>
Run Code Online (Sandbox Code Playgroud)

CSS:

* {
    margin:0;
    padding:0;
}
section article[id] * {
    clear: both;
    float: left;
    height: auto;
    width: 100%;
}

section article[id] h2 {
    color: #bbb;
}

section article[id] h3 {
    color: #aaa;
}

section article[id] h4 {
    text-align: justify;
}


/* THIS IS NOT WORKING !!! */
section article[id] h4:first-child { /* :first-of-type */
    text-indent: 10px;
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle演示.

Has*_*ami 13

那是因为<h4>它不是其父母的第一个孩子.

element:first-child表示其父级的第一个子级,匹配element.在这个特定的例子中,第一个元素<article>是一个<h2>元素; 不是<h4>.

您可以使用:first-of-type伪类来选择<h4>其父子树中的第一个元素,如下所示:

section article[id] h4:first-of-type {
    text-indent: 10px;
}
Run Code Online (Sandbox Code Playgroud)

工作演示.

来自MDN:

:first-of-typeCSS伪类表示它的类型在其父元素的子列表中的第一个兄弟.