css - 在一个元素中使用两个类有什么意义?

标签 css css-selectors

<!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/

相关文章:

html - 缺少底部的网络表单

c# - 如何在面板中并排设置控件

css - 位置 :absolute within border-radius and overflow:hidden

css - 如何在 Material-UI Grid 行中垂直对齐我的元素?

css - :nth-child within Bootstrap rows

html - 定位无序列表列表项中的第一个和最后一个 anchor

javascript - 两行时减小跨度文本的字体大小

css - :first-child selector not applying in emotion css

css - 分组 .className + 媒体查询?

css - 如何使用悬停选择器显示 "uncle"元素