特定类型的第一个子元素

时间:2013-06-02 04:06:58

标签: html css css-selectors

我有一些有三个孩子的部分(一个<h1>和两个<div>

<section class="half">
  <h1>Half</h1>
  <div>
    left half
  </div>
  <div>
    right half
  </div>
</section>

然后我在这些块中添加一些样式

section > h1 { ... }
section > div { ... }

我想为该部分中的第一个<div>元素指定其他样式。

我不能只使用section > :first-child来使用,因为部分中的第一个孩子是<h1>

那我应该怎么写?

4 个答案:

答案 0 :(得分:4)

这就是:nth-of-type的用途:

section > div:nth-of-type(1) {
    /* CSS properties go here... */
}

答案 1 :(得分:3)

您正在寻找:first-of-type

答案 2 :(得分:1)

仅使用section > div:nth-of-type(1) {将选择父元素为div的第一个section元素,因此我觉得它将是一个松散的选择器,使用

更严格
section.half > div:nth-of-type(1) { /* This will select 1st div element inside
                                     * section having class .half
                                     */
    /* Styles goes here */
}

Demo

您还可以使用first-of-type Demo

section.half > div:first-of-type {
    /* Styles goes here */
}

答案 3 :(得分:1)

Working jsFiddle Demo

毫无疑问,Joseph Silber answer很棒。但是如果你不想使用CSS3,这就是诀窍:

section > div { background: red; }
section > div + div { background: transparent; }

首先,选择所有 div元素并为其设置属性。然后,您选择第二个div,然后选择 为它重置这些属性。