如何选择包含两个类的元素?

时间:2013-10-09 21:12:58

标签: html css css-selectors

我有这个HTML:

<h2 class="first second">Red</h2>
<h2 class="second">Blue</h2>
<h2 class="first">Green</h2>

如何选择h2firstsecond

感谢答案

<小时/> 的更新

如果我有另一个h2标签,请执行以下操作:

<h2 class="first second third">Default</h2>

h2.first.second选择器将显示为红色。有没有办法只选择firstsecond类的元素,而不是更多。

6 个答案:

答案 0 :(得分:5)

简单地:

h2.first.second {
    color: red;
}

这将选择具有“first”和“second”两个类的h2元素。有关详细信息,请参阅CSS Selectors Level 3 W3建议。

JSFiddle demo

答案 1 :(得分:2)

如果你试图同时选择第一和第二类的h2

  

h2.first.second

答案 2 :(得分:2)

我已经创建了working CodePen example解决方案。

h2.first.second {
/* styles go here*/
}

答案 3 :(得分:2)

要选择具有多个类的元素,请使用:

h2.first.second

请注意,类之间没有空格,如下所示,它将选择类second的元素,这些元素位于h2元素中,类为first

h2.first .second

答案 4 :(得分:1)

您可以选择

.first.second {}

如果您只想选择第一个h2。确保没有空间!

答案 5 :(得分:1)

以下规则与任何h2元素匹配,该元素的类属性已分配了以空格分隔的值列表包括“first”和“second”:

h2.first.second { color: red }

Reference

但是,要选择其类属性完全相等“first”和“second”的元素,我使用了这条规则:

h2[class="first second"], h2[class="second first"] { color: red }

JsFiddle demo.

相关问题