How to select multiple elements that are children

2020-05-19 06:06发布

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

I could do it this way:

div#mydiv > pre, div#mydiv > div

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

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?

3条回答
Viruses.
2楼-- · 2020-05-19 06:47

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.

查看更多
Summer. ? 凉城
3楼-- · 2020-05-19 07:02

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

#mydiv > * {

which will apply to all elements that are children of that 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.

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-19 07:10

You'll have to reference #mydiv twice...

#mydiv > pre, #mydiv > div

I removed the extraneous div element selector as the ID is specific enough.

查看更多
登录 后发表回答