How do I select an element only when inside another element?(如何仅在另一个元素内选择一个元素?)
问题描述
我有一个关于 CSS 选择器的问题.仅当 <ul>
具有类名 saft
时,如何选择具有特定类名的 <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 Fiddle 演示.
在这种情况下,应用于 textSlide
类的 div
的规则仅适用于其祖先是 类的
.相反,您可以使用直接子组合子 ul
>安全>
但随后您必须指定与每个父/祖先相关的 div
直到其class 是必需的,这可能会使 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).
这篇关于如何仅在另一个元素内选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!