CSS选择器仅当在另一个元素内时选择元素 [英] CSS selectors Selecting an element only when inside another element

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

问题描述

我有一个关于CSS选择器的问题。如何使用特定类名选择< div> ,只有当它位于< ul> 类名 saft ?这个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 Fiddle demo

在这种情况下,规则应用于类的 div code> textSlide 仅适用于其祖先是 saft ul c>。你可以使用立即子组合器> ,但是你必须指定 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).

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

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