使用CSS选择第一个后代 [英] Select first Descendant with CSS

查看:202
本文介绍了使用CSS选择第一个后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否仍然使用CSS选择第一个后代。例如,是否还有从.container元素开始,并设置< li class =example>具有蓝色边框,但不包括< p class =example>在里面?

Is there anyway to select only the first descendant using CSS. For example, is there anyway to start at the .container element and style the <li class="example"> with a blue border, but not the <p class="example"> within it?

我知道在CSS中有很多其他方法可以实现。但是有没有办法用下面的确切代码?意思只使用选择器类.container和.example,将类.container完全放在下面的HTML中,并使用下面的HTML标记。

I know there are a ton of alternative ways to to this in CSS. But is there a way to do it with the exact code below? Meaning use only the selector classes .container and .example, leave the class .container exactly where it is within the HTML below, and use the exact HTML markup below.

<style>
    .container .example{
        border: 1px solid blue;
    }
</style>

<div>
    <div class="container">
        <ul>
            <li class="example"><p class="example"></p></li>
            <li class="example"><p class="example"></p></li>
        </ul>
    </div>
</div>


推荐答案

/ p>

Do you mean the "direct child selector"?

.container > ul > li

..这里是你的蓝色边框:

..here it is your blue border:

.container > ul > li {
    border: solid 1px #00f;
}

..只能使用类, / p>

..to only use classes, you can accomplish that with something like:

.container > * > .example{
    border: solid 1px #00f;
}



选择第一个层次结构



css2方法(我仍然更健壮)添加边框到 .example 并从 .example .example中移除

.example{
    border: solid 1px #00f;
}
.example .example{
    border: none;
}



在CSS3中,您可以执行此操作:

In CSS3, you can do this:

:not(.example) > .example{
    border: solid 1px #00f;
}

请注意,这不会 c $ c> .example> div> .example 也不能获得蓝色边框..
但是它保证没有 .example 是另一个的直接子<$ c $

just beware that this will not prevent .example > div > .example from getting the blue border too.. but it guarantees no .example that is direct child of another .example will get that style.

.container:not(.example)> .example

我不知道你可以用cleancss做得更好。

I don't thing you can do better with "clean" css (ie. single rule; without resetting etc.).

not()选择器的意思是匹配与选择器不匹配的任何项目 not禁止此选择器匹配规则中的某处。

The meaning of not() selector is "match any item that doesn't match the selector", not "forbid this selector to match somewhere here in the rule"..

这篇关于使用CSS选择第一个后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆