【问题标题】:Style the first legend element within a nested fieldsets为嵌套字段集中的第一个图例元素设置样式
【发布时间】:2016-02-23 06:24:29
【问题描述】:

我正在尝试为嵌套字段集中的第一个 legend 元素设置样式,但我使用的 CSS 选择器都没有实现我所追求的。

http://codepen.io/anon/pen/epodxd

如果可能的话,我基本上想在不使用任何其他 CSS 类的情况下为第一个图例元素设置样式。

<fieldset class="nested-parent">
    <legend>Parent</legend>
    <input type="text" size="10" />

    <fieldset>
        <legend>Child</legend>
        <input type="text" size="20" />
    </fieldset>
</fieldset>
.nested-parent legend:first-child {
  color: red;
}

【问题讨论】:

    标签: css legend fieldset


    【解决方案1】:

    根据您提供的 HTML,您可以使用 child selector, &gt; 来选择第一个 legend 元素,它是 .nested-parent 元素的直接子元素:

    .nested-parent > legend:first-child {
      color: #f00;
    }
    

    我建议改用:first-of-type pseudo class。在处理元素的类型时会更准确。

    Example Here

    .nested-parent > legend:first-of-type {
      color: #f00;
    }
    

    【讨论】:

    • 无论如何,图例只能是有效 HTML 文档中字段集的第一个子项,因此无论您使用 :first-child 还是 :first-of-type 可能都不会产生影响(除非您正在处理无效标记)。但这里的关键是使用带有特定字段集的子选择器,您要针对其子图例。
    • @BoltClock 啊,好点。我不知道!我想这只会涵盖当时存在无效标记的情况..
    • 非常感谢 Josh 和 BoltClock!
    猜你喜欢
    • 2021-04-25
    • 2010-10-14
    • 2016-12-13
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2014-07-15
    相关资源
    最近更新 更多