CSS 如何仅在另一个元素内选择一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11863423/
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
How do I select an element only when inside another element?
提问by RonanC
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.
我有一个关于 CSS 选择器的问题。<div>
仅当它在<ul>
具有类名的a 中时,如何选择具有特定类名的a saft
?这个 CSS 类在别处使用,我不想在任何地方更改样式。
<div id="floater">
<ul class="saft">
<li><div class="textSlide"></li>
</ul>
</div>
回答by David says reinstate Monica
Simply use the CSS descendant selector (a space) between the parent element and the descendant element:
只需在父元素和后代元素之间使用 CSS 后代选择器(一个空格):
ul.saft div.textSlide {
/* CSS rules */
}
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).
在这种情况下,应用于div
of 类的规则textSlide
仅在其祖先是ul
类的a 时才适用saft
。相反,您可以使用直接子组合器,>
但随后您必须指定与div
每个父/祖先的关系,直到需要其类的那个,这可能难以维护 CSS(不是在这种情况下,但随着时间的推移,它可能会成为问题)。
回答by Andy
Just do:
做就是了:
ul.saft .textSlide {
ul.saft .textSlide {
This achieves what you need
这实现了你所需要的
回答by Shailender Arora
you can easily select a div with a specific class name only when its inside a UL with a class name saft like mentioned below css :-
您可以轻松地选择具有特定类名的 div,只有当它位于 UL 内时,其类名 saft 如下面 css 所述:-
ul.saft .textSlide {
color:red;
}
or see the demo :- http://tinkerbin.com/mcrh7iMq
或查看演示:- http://tinkerbin.com/mcrh7iMq