【问题标题】:How to style for first-child of a certain type of element?如何为某种类型的元素的第一个孩子设置样式?
【发布时间】:2018-03-20 03:08:26
【问题描述】:

例如,我有类似的 HTML:

<div class='page'>
    <span>2</span>
    <span>2</span>
    <a>1</a>
    <a>6</a>
</div>

如何为第一个孩子设置样式

我是这样使用的:.page a:first-child {color:red}

但它没有运行。

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    使用 first-of-type 代替 first-child

    .page a:first-of-type{
        color:red;
    }
    

    :first-of-type CSS 伪类表示其父元素的子元素列表中其类型的第一个兄弟。

    取自MDN Documentation。您可以找到更多详细信息和示例here.

    解释::first-child not working as expected

    【讨论】:

      【解决方案2】:

      正如 Pranav c 所说,您可以使用 .page a:first-of-type { ... }.page a:nth-of-type(1) { ... } 但它们都不能在 IE8

      中工作

      因此,如果我们可以假设&lt;span&gt; 始终存在,那么

      .page span+a { ... }
      

      将确保仅设置跨度后的第一个 a 样式,这与您现在可以跨浏览器一样好。

      示例:FIDDLE

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-03
        • 2021-04-25
        • 1970-01-01
        • 2012-01-20
        • 2023-03-07
        • 2011-01-01
        • 2011-11-26
        • 2013-12-11
        相关资源
        最近更新 更多