Html 只为父级而不是子级应用 css
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16787178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
applying css for only parent but not to children
提问by Robz
I have an unordered list like this:
我有一个这样的无序列表:
<div class="list">
<ul>
<li>
list1
<ul>
<li>Sub list1</li>
<li>Sub list2</li>
<li>Sub list3</li>
</ul>
</li>
<li>
list2
<ul>
<li>Sub list1</li>
<li>Sub list2</li>
<li>Sub list3</li>
</ul>
</li>
</ul>
</div>
I now want to apply CSS only for the first list but not its children ul
and li
. I've attempted the following:
我现在只想将 CSS 应用于第一个列表,而不是它的子项ul
和li
. 我尝试了以下操作:
.list ul li{
background:#ccc;
}
...but the background color is applied to all lists. What should be done to change the CSS of only parent but not the children.
...但背景颜色适用于所有列表。应该怎么做才能改变父级而不是子级的 CSS。
回答by Guffa
Use the direct descendant operator >
for that:
>
为此使用直接后代运算符:
.list > ul > li { ... }
The >
operator selects only elements that are direct children of the element(s) before it.
该>
运算符仅选择作为其之前元素的直接子元素的元素。
Note however, anything inside that list item will of course have the background of the list item despite not having any background color directly assigned to it.
但是请注意,该列表项中的任何内容当然都会具有列表项的背景,尽管没有直接为其分配任何背景颜色。
回答by Johan
You can use the > operator for that, like this:
您可以为此使用 > 运算符,如下所示:
.list > ul > li{
background:#ccc;
}
回答by Kees Sonnema
The only way of doing this is like:
这样做的唯一方法是:
.List > ul > li { background-color: #ccc; }
If you want to apply only the bgcolor to the ul simply do:
如果您只想将 bgcolor 应用于 ul 只需执行以下操作:
.List > ul { background-color: #ccc; }
:)
:)
回答by pro-tester
Alternatively, you can now do:
或者,您现在可以执行以下操作:
li:not(li li) { background: #ccc; }