我一直在使用ID加后代样式规则,以使div的所有后代没有填充且没有边距。但是我注意到它比ID选择器中的样式更具体。
我有多个div。有没有一种方法可以使其不那么具体?
在下面的示例中,由于ID + *更具体,因此未应用填充和边框:
#list1item1 {
padding-left: 10px;
outline: 1px dashed green;
}
#list2item1 {
padding-left: 20px;
outline: 1px dashed blue;
}
#GroceryList1 {
left: 40px;
top: 20px;
position: absolute;
}
#GroceryList2 {
left: 200px;
top: 20px;
position: absolute;
}
#GroceryList1 * {
margin: 0;
padding: 0;
outline: none;
}
#GroceryList2 * {
margin: 0;
padding: 0;
outline: none;
}
<div id="GroceryList1">
<ol>
<li id="list1item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
<div id="GroceryList2">
<ol>
<li id="list2item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
无需切换到类,是否可以选择div的所有后代,而常规ID选择器更具体?
答案 0 :(得分:3)
您可以使用以GroceryList
字符串开头的属性选择器(但不能使用字符串后面的数字)。
[id^=GroceryList] * {
margin: 0;
padding: 0;
outline: none;
}
这不会覆盖您定义的更具体的填充规则。
#list1item1 {
padding-left: 10px;
outline: 1px dashed green;
}
#list2item1 {
padding-left: 20px;
outline: 1px dashed blue;
}
#GroceryList1 {
left: 40px;
top: 20px;
position: absolute;
}
#GroceryList2 {
left: 200px;
top: 20px;
position: absolute;
}
[id^=GroceryList] * {
margin: 0;
padding: 0;
outline: none;
}
<div id="GroceryList1">
<ol>
<li id="list1item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
<div id="GroceryList2">
<ol>
<li id="list2item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
答案 1 :(得分:1)
通配符选择器:[id^="GroceryList"]
第一类选择器:li:first-of-type
现在在一起!
#GroceryList1 {
left: 40px;
top: 20px;
position: absolute;
}
#GroceryList2 {
left: 200px;
top: 20px;
position: absolute;
}
/* now overridden by below selector */
[id^="GroceryList"] * {
margin: 0;
padding: 0;
outline: none;
}
[id^="GroceryList"] ol li:first-of-type {
padding-left: 10px;
outline: 1px dashed green;
}
/* override rule above */
#list2item1 {
padding-left: 20px;
outline: 1px dashed blue;
}
<div id="GroceryList1">
<ol>
<li id="list1item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
<div id="GroceryList2">
<ol>
<li id="list2item1">Bread
<li>Stick of Butter
<li>Gallon of milk
</ol>
</div>
的帮助下