:first-child is not working to select the first h4

2019-02-26 03:10发布

问题:

I was wondering why I can't indent the :first-child of h4.

All the rest of the h4 elements should not be indented.

The 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>

The 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;
}

The jsFiddle demo.

回答1:

That's because the <h4> is not the first child of its parent.

element:first-child represents the first child of its parent, matching the element. And in this particular instance, the first element of <article> is a <h2> element; Not the <h4>.

You could use :first-of-type pseudo class to select the first <h4> element in its parent's children tree, as follows:

section article[id] h4:first-of-type {
    text-indent: 10px;
}

WORKING DEMO.

From the MDN:

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.



回答2:

Try h4:first-of-type instead, because the first child of the parent element is not a <h4>



回答3:

The answer was, in fact, in your fiddle you just didn't use it.

JSFiddle

 /* :first-of-type */
section article[id] h4:first-of-type {
    text-indent: 10px;
}