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).
这篇关于如何仅在另一个元素内选择一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅在另一个元素内选择一个元素?
基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
