CSS selector - element with a given child(CSS 选择器 - 具有给定子元素的元素)
问题描述
我正在寻找一个选择器,如果它们具有特定的子元素,它将选择所有元素.例如,选择所有 <div>
与子 <span>
.
I'm looking to make a selector which will select all elements if they have a specific child element. For example, select all <div>
with a child <span>
.
可能吗?
推荐答案
如果元素包含特定的子元素,是否可以选择它?
Is it possible to select an element if it contains a specific child element?
很遗憾还没有.
CSS2 和 CSS3 选择器规范不允许任何类型的父选择.
The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.
这是关于从现在开始这篇文章的准确性的免责声明.CSS 中的父选择器已经讨论了很多年.由于尚未达成共识,因此不断发生变化.我会尽量保持这个答案是最新的,但是请注意,由于规范的变化,可能会有不准确的地方.
This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.
较早的Selectors Level 4 Working Draft" 描述了一个特性,即能力指定 主题";一个选择器.此功能已被删除,将无法用于 CSS 实现.
An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.
主题将是选择器链中应用样式的元素.
The subject was going to be the element in the selector chain that would have styles applied to it.
<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>
此选择器将为 span
元素设置样式
This selector would style the span
element
p span {
color: red;
}
此选择器将为 p
元素设置样式
This selector would style the p
element
!p span {
color: red;
}
最近的Selectors Level 4 Editor's Draft" 包括The关系伪类::has()
"
A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()
"
:has()
将允许作者根据其内容选择元素.我的理解是选择它来提供与 jQuery 的自定义 :has()
伪选择器*.
:has()
would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has()
pseudo-selector*.
无论如何,继续上面的示例,选择包含 span
的 p
元素,可以使用:
In any event, continuing the example from above, to select the p
element that contains a span
one could use:
p:has(span) {
color: red;
}
* 这让我想知道 jQuery 是否已经实现了选择器主题,主题是否会保留在规范中.
这篇关于CSS 选择器 - 具有给定子元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CSS 选择器 - 具有给定子元素的元素
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01