我可以在CSS中分组子元素吗? [英] Can I group subelements in CSS?

查看:76
本文介绍了我可以在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;}

这篇关于我可以在CSS中分组子元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆