我有以下html:
<div class="widget1">
<p class="rule1"></p>
<p class="rule2"></p>
<p class="rule3"></p>
</div>
<div class="widget2">
<p class="rule1"></p>
<p class="rule2"></p>
<p class="rule3"></p>
</div>
我有以下规则:
.rule1 {
color: red;
}
.rule2 {
color: green;
}
.rule3 {
color: blue;
}
我只想将这些规则应用于widget1,而不是widget2。
我知道这有效:
widget1 .rule1 {
color: red;
}
widget1 .rule2 {
color: green;
}
widget1 .rule3 {
color: blue;
}
但是,我想要将30个规则应用于widget1。是否有选择器做这样的事情?
.widget1 {
.rule1 {
color: red;
}
.rule2 {
color: green;
}
.rule3 {
color: blue;
}
}
更新
寻求一种好方法的全部目的是简化CSS并避免使用相同的通用规则覆盖不同小部件(例如.rule1 .rule2 .rule3)
答案 0 :(得分:1)
我会根据需要创建“群组”规则并将其添加到您的元素中。
的内容
/* all p elements as group */
.widget1 p {
border: 2px solid black;
}
/* other elements (not necessarily a p) as a group */
.widget1 .common {
min-height: 50px;
padding: 10px;
margin: 5px;
color: white;
}
.widget1 .rule1 {
width: 100px;
background-color: red;
}
.widget1 .rule2 {
width: 200px;
background-color: green;
}
.widget1 .rule3 {
width: 150px;
background-color: blue;
}
.widget1 .mute {
color: grey;
}
<div class="widget1">
<p class="common rule1">1.1</p>
<p class="common rule2 mute">1.2</p>
<p class="common rule3">1.3</p>
<div class="common rule1 mute">1.4 (notice no border here)</div>
</div>
<div class="widget2">
<p class="rule1">2.1</p>
<p class="rule2">2.2</p>
<p class="rule3">2.3</p>
</div>
答案 1 :(得分:-2)
编辑。
您可以使用p:nth-child(1)
查看小提琴https://jsfiddle.net/rfb31uto/3/
.widget1 > p:nth-child(1) {
background-color: red;
}
.widget1 > p:nth-child(2) {
background-color: blue;
}
.widget1 > p:nth-child(3) {
background-color: green;
}
或者这个:
.widget1 > .rule1{
background-color: red;
}
.widget1 > .rule2{
background-color: blue;
}
.widget1 > .rule3{
background-color: green;
}
或者这个:
.widget1 > p:nth-child(3n+0){
background-color: red;
}
.widget1 > p:nth-child(3n-2){
background-color: blue;
}
.widget1 > p:nth-child(3n-1){
background-color: green;
}