html - 我可以在 CSS 中对子元素进行分组吗?

标签 html css css-selectors

假设我有一个像这样的小 html 区域:

<div id="somecontainer">
   <h1>text</h1>
   <h2>text</h2>
   <h3>text</h3>
   <p>text</p>
</div>

现在我想使用 CSS 对该容器的几个子元素进行样式设置。 目前我是这样做的,但它看起来比它可能需要的更复杂:

#somecontainer h1,#somecontainer h3,#somecontainer p { color:red; }

有什么办法可以对 CSS 代码的这些子元素进行“分组”,这样我就不必三次提及容器 ID #somecontainer 吗?

我想象可能有一个类似运算符的东西,它会将语法变成类似 #somecontainer h1+h3+p 的东西(对于这个例子,+ 将被假定为这样运算符(operator))。 CSS中有这样的东西吗?

最佳答案

使用纯 CSS,这将针对 #somecontainer 的所有直接子级:

#somecontainer > *

然后您可以恢复在 H2 上设置的任何内容。例如

#somecontainer > * {color: red;}
#somecontainer > h2 {color: black};

但这并不是一种特别有效的编写方式。我会坚持显式编写类,或者理想情况下考虑使用像 Less 这样的预处理器或Sass ,你可以在其中写下:

#somecontainer {
    h1, h3, p {
        color: red;
    }
}

这会输出你最终想要的,这个 -

#somecontainer h1 {color: red;}
#somecontainer h3 {color: red;}
#somecontainer p {color: red;}

关于html - 我可以在 CSS 中对子元素进行分组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460278/

相关文章:

html - 如何更改CSS中文本的大小?

c# - C# 中的 Selenium 如何根据其值定位此跨度?

css - 我怎样才能防止第 n 个 child 踩到对方的脚趾?

html - 选择嵌套元素的第一个子元素时遇到问题

javascript - JS : Get the . 所选数据列表选项的 html()

jquery - 阻止 CSS 文档在移动设备上加载

html - SVG 不会缩放

html - CSS+HTML 和 IE10

php - CSS 幻灯片不适用于数据库中的图像

html - div 旁边的图像 - HTML