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

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

How to select multiple elements using CSS

csscss-selectors

提问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 inputand textareaelements from the div.c3with only one CSS rule. I'm using

我想将inputtextarea元素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 c3div.

但这匹配所有文本区域,而不仅仅是在c3div中的文本区域。

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 .c3if 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 .c3like 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; }