CSS选择器 - 具有给定子元素 [英] CSS selector - element with a given child

查看:77
本文介绍了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.

旧的选择器4级工作草案描述了能够指定选择器的主题的功能。 此功能已删除,将无法用于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 / p>

This selector would style the span element

p span {
    color: red;
}

这个选择器会将 p 元素

!p span {
    color: red;
}






href =https://drafts.c​​sswg.org/selectors-4/#relational =noreferrer>选择器第4级编辑草案包括关系伪类::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*.

无论如何,继续上面的示例,选择 p 元素包含 span 可以使用:

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选择器 - 具有给定子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆