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

时间:2014-02-28 13:17:05

标签: html css css-selectors

我想知道为什么我不能缩进:first-child的{​​{1}}。

h4元素的所有其余元素不应缩进。

HTML:

h4

CSS:

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

jsFiddle demo

3 个答案:

答案 0 :(得分:13)

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

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

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

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

<强> WORKING DEMO

来自 MDN

  

:first-of-type CSS伪类代表了第一个兄弟   它在父元素子元素列表中的类型。

答案 1 :(得分:4)

请尝试使用h4:first-of-type,因为父元素的第一个子元素不是<h4>

答案 2 :(得分:1)

事实上,答案是在你的小提琴中你没有使用它。

JSFiddle

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