Html 如果它有带有 css 的子项,则将样式应用于父项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21252551/
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
Apply style to parent if it has child with css
提问by Green Wizard
I'm trying to apply styles
to the parent
if it has child
elements.
我想申请styles
到parent
它是否有child
元素。
So far, I've applied styles to the child
elements if present. But I want to style
the parent
if the parent
has child
, using ONLY CSS
.
到目前为止,我已经将样式应用于child
元素(如果存在)。但我想style
的parent
,如果parent
有child
,仅使用CSS
。
following is the html
以下是 html
<ul class="main">
<li>aaaa</li>
<li>aaaa</li>
<li>aaaa</li>
<li>aaaa</li>
<li>aaaa
<ul class="sub">
<li>bbbb</li>
<li>bbbb
<ul>
<li>cccc</li>
<li>cccc</li>
<li>cccc</li>
</ul>
</li>
<li>bbbb</li>
<li>bbbb</li>
<li>bbbb</li>
</ul>
</li>
<li>aaaa</li>
<li>aaaa</li>
<li>aaaa</li>
</ul>
the css
code
该css
代码
* {
margin:0;
padding:0;
text-decoration:none;
}
.main li {
display:inline-block;
background:yellow;
color:green;
}
.main > li > ul > li {
background:orange
}
.main > li > ul > li > ul >li {
background:pink;
}
working FIDDLE
工作小提琴
采纳答案by MildlySerious
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
CSS3 是不可能的。有一个提议的 CSS4 选择器,$
可以做到这一点,它看起来像这样(选择li
元素):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
在此处查看CSS4 选择器列表。
As an alternative, with jQuery, a one-liner you could make use of would be this:
作为替代方案,使用 jQuery,您可以使用的单行代码是这样的:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
然后,您可以继续li.has_sub
在 CSS 中设置样式。