CSS 如何使用CSS选择多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6149658/
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
How to select multiple elements using CSS
提问by Quamis
I have the following markup:
我有以下标记:
<div class="c1">
<div class="c2">
<div class="c3">
<input>
<textarea></textarea>
</div>
<input>
<textarea></textarea>
</div>
</div>
I want to match the input
and textarea
elements from the div.c3
with only one CSS rule. I'm using
我想将input
和textarea
元素div.c3
与只有一个 CSS 规则相匹配。我正在使用
div.c1 .c2 .c3 input,textarea { border: 1px solid #f00; }
but this matches all textareas, not only the one cotnained in the c3
div.
但这匹配所有文本区域,而不仅仅是在c3
div中的文本区域。
Is this possible, or must I write separate CSS selectors for each element?
这是可能的,还是我必须为每个元素编写单独的 CSS 选择器?
Look at http://jsfiddle.net/Bp3qn/1/for the live example.
查看http://jsfiddle.net/Bp3qn/1/的实时示例。
I updated http://jsfiddle.net/Bp3qn/3/
我更新了http://jsfiddle.net/Bp3qn/3/
I only need the input and textarea contained in the c1->c2->c3 containers to be highlighted, not other combinations.
我只需要突出显示包含在 c1->c2->c3 容器中的 input 和 textarea,而不是其他组合。
回答by Wesley Murch
You don't need the other elements in the selector, unless you onlywant to match .c3
if it is within div.c1 .c2
:
你不需要在选择其他元素,除非你只是想匹配.c3
,如果它是内div.c1 .c2
:
.c3 input,
.c3 textarea {
/* that's it! */
}
If you do (per your edit), use this:
如果您这样做(根据您的编辑),请使用:
div.c1 .c2 .c3 input,
div.c1 .c2 .c3 textarea{
border: 1px solid #f00;
}
Demo: http://jsfiddle.net/wesley_murch/Bp3qn/6/
演示:http: //jsfiddle.net/wesley_murch/Bp3qn/6/
after edit: thats what i'm trying to avoid (my real stylesheet is a lot more complex and css rules are longer, and its getting hard to read)
编辑后:这就是我想要避免的(我真正的样式表要复杂得多,css 规则也更长,而且越来越难以阅读)
In that case, to make things easier just add another class to that .c3
like this:
在这种情况下,为了使事情更容易,只需添加另一个类,.c3
如下所示:
<div class="c3 special">
.c3.special input,
.c3.special textarea{
border: 1px solid #f00;
}
Demo: http://jsfiddle.net/wesley_murch/Bp3qn/7/
演示:http: //jsfiddle.net/wesley_murch/Bp3qn/7/
If you MUST have the selector as small as possible and there are no other children of .c3.special
, just use the star selector (almost never recommended):
如果您必须让选择器尽可能小并且没有其他子.c3.special
选择器,只需使用星形选择器(几乎不推荐):
.c3.special * {border: 1px solid #f00;}
回答by Bart Vangeneugden
div.c1 .c2 .c3 input,.c3 textarea { border: 1px solid #f00; }