<!DOCTYPE html>
<html>
<head>
<style>
.class1.class2 {
background-color: yellow;
}
</style>
</head>
<body>
<div class="class1 class2">
<p>paragraph one</p>
<p>paragraph two</p>
</div>
</body>
</html>
在一个元素中使用两个类,然后用多个类选择器来设置样式,这不是没有意义的吗?当你可以只用一个类选择器来设置一个类的样式时?还是有什么我不明白的?
最佳答案
这样做的两个主要理由是可重用性 和双重类选择器。使用一组可在多个场景中使用的小型 CSS 类设置一个框架。然后将它们的组合应用于您的元素,并在必要时向特定元素应用一些可重用类尚未涵盖的其他样式。
我举一个简单的例子来说明:
.container {
background: #eee;
border: 1px solid orange;
padding: 10px;
margin: 10px;
}
.container.a-super-special-container {
color: darkgreen;
}
.green {
color: darkgreen;
}
<div class="container">
This page is divided into several containers.
</div>
<div class="container">
So let's use a class <i>.container</i> for styling all of them.
</div>
<div class="container a-super-special-container">
This is a super special container. It builds upon the <i>.container</i> class and colors the text. Instead of copying all the definitions of the <i>.container</i> class we just reuse it.
</div>
<div class="container green">
As an alternative to the classes used in the previous container we could use two reusable classes <i>.container</i> and <i>.green</i> and apply the styles of both of them.
</div>
关于css - 在一个元素中使用两个类有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966320/