CSS选择器,适用于具有两个类的元素 [英] CSS Selector that applies to elements with two classes

查看:432
本文介绍了CSS选择器,适用于具有两个类的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以选择一个CSS元素,基于类属性的值设置为两个特定的类。例如,假设我有3个div:

Is there a way to select an element with CSS based on the value of the class attribute being set to two specific classes. For example, let's say I have 3 divs:

<div class="foo">Hello Foo</div>
<div class="foo bar">Hello World</div>
<div class="bar">Hello Bar</div>

我可以写什么CSS只选择列表中的第二个元素,基于它是

What CSS could I write to select ONLY the second element in the list, based on the fact that it is a member of both the foo AND bar classes?

推荐答案

链接两个类选择器(两者之间没有空格):

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}






仍然需要处理像IE6这样的古老的浏览器,注意它没有正确读取链接类选择器:它只会读取最后类选择器( .bar <


If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

为了说明其他浏览器和IE6如何解释这一点,考虑这个CSS:

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

支持的浏览器上的输出为:

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

在IE6上的输出是:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

脚注:


  • 支持的浏览器:

  • Supported browsers:

  1. 未选择,因为此元素只有类 foo

  2. 已选择,因为此元素同时具有 foo c。 。




  1. Not selected as this element only has class foo.
  2. Selected as this element has both classes foo and bar.
  3. Not selected as this element only has class bar.


  • IE6:

  • IE6:


    1. 未选择,因为此元素没有类 bar


    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

  • $ ,因为此元素具有类 bar b $ b

    这篇关于CSS选择器,适用于具有两个类的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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