同一类标签上的CSS嵌套规则

3

我有两个CSS样式,其中第二个样式只想在第一个样式存在时生效。我该如何做?我知道你可以向class标签添加多个类,但似乎不能以相同方式嵌套css标签。

.stat{float: left; width: 200px; height: 40px; padding: 5px; margin: 5px; border: 1px solid #000;}
.stat .red{background-color: #c00;}


<!-- This should have the background color -->
<div class="stat red">

<!-- This should not have the background color -->
<div class="red">

<!-- This should not have the background color -->
<div class="stat">

6
.stat.red 是一个计算机编程中表示样式的代码。这段代码的意思是设置元素的背景色为红色。 - Tim M.
2个回答

7

只需删除空格:

.stat.red{background-color: #c00;}

3

仅供澄清

.stat .red { ... }

或更准确地说,位于类名之间的“ ”被称为后代选择器。在您的情况下,这意味着只有属于具有类“stat”的元素的后代且带有类“red”的元素将被选中。例如:
<div class="stat">
   <div class="red"></div>
</div>

".stat.red"选择器叫什么? - Ben Dauphinee
.xyz 被称为类选择器,只是在您的情况下包含多个类。 - Đinh Carabus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接