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 选择器 - 具有给定子元素的元素


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06