CSS 如何选择作为给定元素的子元素的多个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6192596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:39:56  来源:igfitidea点击:

How to select multiple elements that are children of given element?

csscss-selectors

提问by rsk82

I have <div id='mydiv'>and I need to select all preand divelements that are children of #mydiv.

我有<div id='mydiv'>我需要选择所有pre,并div认为是子元素#mydiv

I could do it this way:

我可以这样做:

div#mydiv > pre, div#mydiv > div

but, can it be done so that #mydivis referenced only once?

但是,它可以做到#mydiv只引用一次吗?

div#mydiv > pre, div

will select all divs on the page regardless if they're children of #mydiv, so the comma isn't a way to do it. Maybe there's another kind of syntax I don't know about?

将选择div页面上的所有s,无论它们是否是 的孩子#mydiv,所以逗号不是一种方法。也许还有另一种我不知道的语法?

采纳答案by Fosco

You'll have to reference #mydivtwice...

你必须参考#mydiv两次...

#mydiv > pre, #mydiv > div

I removed the extraneous divelement selector as the ID is specific enough.

我删除了无关的div元素选择器,因为 ID 足够具体。

回答by Jawad

As far as I know, there is no shorthand for selector grouping.

据我所知,选择器分组没有简写。

See "Selector Grouping".

请参阅“选择器分组”。

Although, with LESS, it is possible in the "Nested Rules" section.

虽然,使用LESS,可以在“嵌套规则”部分。

回答by East of Nowhere

The only way to reference the id only once is to use it with the *selector:

仅引用 id 一次的唯一方法是将其与*选择器一起使用:

#mydiv > * {

which will apply to allelements that are children of that div.

这将适用于该 div 的所有子元素。

Depending on what styles you plan to apply this might be workable (I typically use this to zero-out margins, padding and border styles), but it's still probably best to do it the first way because it makes it easier to make exceptions/changes later down the road.

根据您计划应用的样式,这可能是可行的(我通常使用它来将边距、填充和边框样式归零),但最好还是采用第一种方式,因为这样可以更轻松地进行例外/更改后来在路上。