问题:
I've been using an ID plus descendants style rule to give all descendants of a div no padding and no margin. But I noticed that it's more specific than the styles in ID sel...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I've been using an ID plus descendants style rule to give all descendants of a div no padding and no margin. But I noticed that it's more specific than the styles in ID selector.
I have multiple divs. Is there a way to make it less specific?
In the example below the padding and border is not applied because the ID+* is more specific:
#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>
Without switching to classes is there a way to select all descendants of a div where a regular ID selector is more specific?
回答1:
You could use an attribute selector beginning with the GroceryList
string (but not the number after the string).
[id^=GroceryList] * {
margin: 0;
padding: 0;
outline: none;
}
This would not override the more specific padding rules you've defined.
#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>
回答2:
Wildcard selector: [id^="GroceryList"]
first-of-type selctor: li:first-of-type
All together now!
#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>
With help from this SO: wildcard * in CSS for classes