如何仅在另一个元素内部时选择一个元素? [英] How do I select an element only when inside another element?

查看:74
本文介绍了如何仅在另一个元素内部时选择一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CSS选择器有疑问.仅当在具有类名saft<ul>内时,如何选择具有特定类名的<div>?这个CSS类在其他地方使用,我不想在任何地方更改样式.

I have a question regarding CSS selectors. How do I select a <div> with a specific class name only when its inside a <ul> with a class name saft? This CSS class is used elsewhere and I don't want to change the styling everywhere.

<div id="floater">
    <ul class="saft">
        <li><div class="textSlide"></li>
    </ul>
</div>

推荐答案

只需在父元素和后代元素之间使用CSS后代选择器(空格):

Simply use the CSS descendant selector (a space) between the parent element and the descendant element:

ul.saft div.textSlide {
    /* CSS rules */
}

JS小提琴演示.

在这种情况下,仅当类别textSlideul的祖先是类别saftul时,才适用规则.相反,您可以使用直接子组合器>,但是您必须相对于每个父级/祖先指定div,直到需要其类的父级/祖先,这都可能导致难以维护CSS (不是这种情况,但是随着时间的流逝,它可能会成为问题).

In this case the rules applied to the div of class textSlide will only apply if its ancestor is a ul of the class saft. You could, instead, use the immediate child combinator, the > but then you'd have to specify the div in relation to each parent/ancestor up to the one whose class is required, which gives potentially difficult to maintain CSS (not in this case, but it can, over time, become problematic).

这篇关于如何仅在另一个元素内部时选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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