CSS 基于多个类选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2554839/
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-29 21:50:46  来源:igfitidea点击:

Select element based on multiple classes

csscss-selectors

提问by Ciel

I have a style rule I want to apply to a tag when it has twoclasses. Is there any way to perform this without JavaScript? In other words:

我有一个样式规则,当它有两个类时,我想将其应用于标签。有没有办法在没有 JavaScript 的情况下执行此操作?换句话说:

<li class='left ui-class-selector'>

I want to apply my style rule onlyif the lihas both .leftand .ui-class-selectorclasses applied.

li同时应用.left.ui-class-selector类时,我才想应用我的样式规则。

回答by Felix Kling

You mean two classes? "Chain" the selectors (no spaces between them):

你是说两个班?“链接”选择器(它们之间没有空格):

.class1.class2 {
    /* style here */
}

This selects all elements with class1that also have class2.

这将选择与所有元素class1也有class2

In your case:

在你的情况下:

li.left.ui-class-selector {

}

Official documentation : CSS2 class selectors.

官方文档:CSS2 类选择器



As akamikepoints out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

正如akamike在 Internet Explorer 6 中指出此方法的一个问题,您可能想阅读以下内容:在 IE6 CSS 中使用双类?

回答by nidhi0806

Chain selectors are not limited just to classes, you can do it for both classes and ids.

链选择器不仅限于类,您可以对类和 id 进行选择。

Classes

班级

.classA.classB {
/*style here*/
}

Class & Id

班级号

.classA#idB {
/*style here*/
}

Id & Id

身件和身件

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

目前所有好的浏览器都支持这个,除了 IE 6,它根据列表中的最后一个选择器进行选择。所以“.classA.classB”将根据“.classB”进行选择。

For your case

对于您的情况

li.left.ui-class-selector {
/*style here*/
}

or

或者

.left.ui-class-selector {
/*style here*/
}

回答by bahman parsamanesh

You can use these solutions :

您可以使用这些解决方案:

CSS rules applies to all tags that have following two classes :

CSS 规则适用于所有具有以下两个类的标签:

.left.ui-class-selector {
    /*style here*/
}

CSS rules applies to all tags that have <li>with following two classes :

CSS 规则适用于所有<li>具有以下两个类的标签:

li.left.ui-class-selector {
   /*style here*/
}

jQuery solution :

jQuery 解决方案:

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

Javascript 解决方案:

document.querySelector("li.left.ui-class-selector").style.color = "red";