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).
这篇关于如何仅在另一个元素内选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅在另一个元素内选择一个元素?
基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
