我可以在CSS中分组子元素吗?
假设我有一个像这样的小html区域:
Let's say I have a small html area like this:
<div id="somecontainer">
<h1>text</h1>
<h2>text</h2>
<h3>text</h3>
<p>text</p>
</div>
现在我想用CSS为该容器的几个子元素设计样式。
目前我这样做,但它看起来比它可能是更复杂:
And now I want to style several subelements of that container with CSS. Currently I do it this way, but it looks more complicated than it might have to be:
#somecontainer h1,#somecontainer h3,#somecontainer p { color:red; }
有什么办法我可以把CSS代码的子组件group不必提到容器ID #somecontainer
三次?
Is there any way I can kinda "group" those subelements for the CSS code, so I don't have to mention the container-ID #somecontainer
three times?
我想像一个像运算符将使语法变成类似 #somecontainer h1 + h3 + p
(对于本示例 +
将被假定为这个操作符)。在CSS中有这样的事情吗?
I imagine maybe something like an operator which would make the syntax into something like #somecontainer h1+h3+p
(for this example +
would be assumed to be this operator). Is there such a thing in CSS?
使用纯CSS,这将面向#somecontainer的所有直接子:
With pure CSS, this will target all direct children of #somecontainer:
#somecontainer > *
然后你可以还原H2上设置的任何内容。例如
And then you can revert whatever you have set on the H2. For example
#somecontainer > * {color: red;}
#somecontainer > h2 {color: black};
但这不是一种特别有效的编写方式。我会坚持明确地写这些类,或者最好使用像 Less 或 Sass ,您可以在这里写下:
But it's not a particularly efficient way of writing it. I would stick to explicitly writing the classes, or ideally looking into using a preprocessor like Less or Sass, where you could write this:
#somecontainer {
h1, h3, p {
color: red;
}
}
这将输出你最终想要的, / p>
which would ouput what you ultimately want, this -
#somecontainer h1 {color: red;}
#somecontainer h3 {color: red;}
#somecontainer p {color: red;}