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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:36:44  来源:igfitidea点击:

Apply style to parent if it has child with css

htmlcss

提问by Green Wizard

I'm trying to apply stylesto the parentif it has childelements.

我想申请stylesparent它是否有child元素。

So far, I've applied styles to the childelements if present. But I want to stylethe parentif the parenthas child, using ONLY CSS.

到目前为止,我已经将样式应用于child元素(如果存在)。但我想styleparent,如果parentchild,仅使用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 csscode

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 lielement):

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_subin your CSS.

然后,您可以继续li.has_sub在 CSS 中设置样式。