【问题标题】:How to assign all elements with a certain tag to a certain class?如何将具有某个标签的所有元素分配给某个类?
【发布时间】:2015-03-29 11:30:03
【问题描述】:

在 CSS 中,我有:

.white {color:white}

在 HTML 中,我有:

<div class="foo">
    <div>Text here</div>
    <div>Text here</div>
    <div>Text here</div>
<div>

我希望“foo” div 中的所有 div 都在“white”类中,而不必在每个 div 中显式编写它。这个属性是怎么调用的,在 CSS 中怎么写?

谢谢!

【问题讨论】:

  • 此时,只需将类 white 添加到具有类 foo 的 div 中,与将类 white 添加到所有底层 div 的结果相同,因为这些是子 div。因此,仅将其应用于 div foo 即可达到您尝试实现的效果,即文本颜色为白色。

标签: css class


【解决方案1】:

你不能以声明方式添加类,但 CSS 规则

.foo > div {
    color:white
}

将匹配所有divs 类的直接后代foo:(我更改了我的示例的属性,否则你什么都看不到:)

.white, .foo > div {
    background-color: blue
  }
<div class="foo">
  <div>Line 1</div>
  <div>Line 2</div>
</div>

sass 或 less 等 CSS 预处理器可以帮助您使用它们自己的机制,因此您不必对规则适用的位置进行冗长的枚举。 (在他们的文档中查找“mixins”或“inheritance”。)

【讨论】:

    【解决方案2】:

    有两种方法可以回答你的问题,我能想到的。

    1) 使用JQuery,您可以将白色类添加到 foo div 元素的所有子元素。

    2) 将白色类添加到 foo 类 div 元素,这会将样式向下级联到所有子元素,从而级联样式表..

    <div class="foo white"> <div>Text here</div> <div>Text here</div> <div>Text here</div> <div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-27
      • 2011-10-11
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 2012-06-06
      相关资源
      最近更新 更多