【问题标题】:Select first element in div选择div中的第一个元素
【发布时间】:2021-10-10 09:41:26
【问题描述】:

当你不知道第一个元素是什么时,是否可以解决div中的第一个元素。

例如,我有两个不同的 div

<div class="templateOne">
 <h1>Header 1</h1>
</div>

<div class="templateOne">
 <h2>Header 2</h2>
</div>

那我可以说

.templateOne > * {
 margin-top: 0em;
}

或类似的东西。

【问题讨论】:

    标签: html css styles


    【解决方案1】:

    > child combinator

    * universal selector

    :first-child

    .templateOne > *:first-child {
      margin-top: 0em;
    }
    

    【讨论】:

    • .templateOne :first-child 作为选择器就足够了。
    【解决方案2】:

    如果要使用第一个子元素的地址,可以使用:first-child:nth-child(1) 伪选择器。

    .templateOne :first-child {
      color: red;
    }
    <div class="templateOne">
      <h1>Header 1</h1>
      <p>Content 1</p>
    </div>
    
    <div class="templateOne">
      <h2>Header 2</h2>
      <p>Content 2</p>
    </div>

    如果您只想处理具有特定类名的第一个元素,您可以使用:first-of-typenth-of-type(1)

    .templateOne:first-of-type {
      color: red;
    }
    <div class="templateOne">
      <h1>Header 1</h1>
      <p>Content 1</p>
    </div>
    
    <div class="templateOne">
      <h2>Header 2</h2>
      <p>Content 2</p>
    </div>

    【讨论】:

      猜你喜欢
      • 2015-12-06
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多