如何将两个 CSS 类应用到单个元素

我是否可以将两个类应用于单个 divspan或任何 HTML 元素? 例如:

<a class="c1" class="c2">aa</a>

我试过了,在我的情况下 c2没有得到应用。我怎样才能同时应用这两个类?

237304 次浏览

1) Use multiple classes inside the class attribute, separated by whitespace (裁判):

<a class="c1 c2">aa</a>

2)为了定位包含所有指定类的元素,使用 CSS 选择器(没有空间)(裁判) :

.c1.c2 {
}

将这两个类字符串包含在单个类属性值中,中间有一个空格。

<a class="c1 c2" > aa </a>

正如其他人指出的那样,你只需用一个空格来划分它们。

但是,了解选择器的工作方式也很有用。

考虑一下这段 HTML..。

<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>

Using .a { ... } as a selector will select the first and third. However, if you want to select one which has both a and b, you can use the selector .a.b { ... }. Note that this won't work in IE6, it will simply select .b (the last one).

<a class="c1 c2">aa</a>

This is very clear that to add two classes in single div, first you have to generate the classes and then combine them. This process is used to make changes and reduce the no. of classes. Those who make the website from scratch mostly used this type of methods. they make two classes first class is for color and second class is for setting width, height, font-style, etc. 当我们合并这两个类时,第一个类和第二个类都在 效果。

.color
{background-color:#21B286;}
.box
{
width:"100%";
height:"100px";
font-size: 16px;
text-align:center;
line-height:1.19em;
}
.box.color
{
width:"100%";
height:"100px";
font-size:16px;
color:#000000;
text-align:center;
}
<div class="box color">orderlist</div>

用空格把他们分开。

<div class="c1 c2"></div>

.color
{background-color:#21B286;}
.box
{
width:"100%";
height:"100px";
font-size: 16px;
text-align:center;
line-height:1.19em;
}
.box.color
{
width:"100%";
height:"100px";
font-size:16px;
color:#000000;
text-align:center;
}
<div class="box color">orderlist</div>

In practice, two classes are used for an element when the two classes format 不同的不重叠 areas, e.g., one class specifies the color and the other the alignment of text. Then you use these two classes for an element and don't need to write a third class that is the amalgam of the other two, see my source code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example</title>
<style>
.color-red         {color: red;        }
.center-align-text {text-align: center;}
</style>
</head>
<body style="width:500px; background-color:lightgray">
<p style="width:400px;background-color:white"
class="color-red center-align-text">Centered pepperoni</p>
</body>
</html>