gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:49:03 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com