有 CSS 父选择器吗?
如何选择锚定元素的直接父元素的< li>
元素?
例如,我的CSS将是这样的:
li < a.active {
property: value;
}
JavaScript执行此操作,但我希望有某种解决方法存在于CSS 2级。
显然有一些方法可以使用 正在由CMS吐出,因此我无法将活动元素移至&lt; li&gt;
元素...(除非我主题为菜单创建模块,否则我不想做) 。
How do I select the <li>
element that is a direct parent of the anchor element?
As an example, my CSS would be something like this:
li < a.active {
property: value;
}
Obviously there are ways of doing this with JavaScript, but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.
The menu that I am trying to style is being spewed out by a CMS, so I can't move the active element to the <li>
element... (unless I theme the menu creation module which I'd rather not do).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
W3C 的选择器级别 4 工作草案包括 a
:has()
提供此功能的伪类,除其他外:所有主要浏览器都支持此选择器。请参阅https://caniuse.com/css-has检查您的目标浏览器或浏览器版本是否有支持它。
如果您的目标浏览器不完全支持此功能,您可能需要使用 JavaScript。
The W3C's Selectors Level 4 Working Draft includes a
:has()
pseudo-class that provides this capability, among others:All major browsers support this selector. Refer to https://caniuse.com/css-has to check if your target browser or browser versions have support for it.
You may need to resort to using JavaScript if your target browser does not fully support this feature.
您可以使用
:has()
css pseudo-class < /a>。请参阅caniuse.com 请参阅浏览器支持。
You can use the
:has()
CSS pseudo-class.See browser support at Caniuse.com.
我认为你不能只在 CSS 中选择父级。
但由于您似乎已经有一个
.active
类,因此将该类移动到li
(而不是a
)会更容易。这样您就可以仅通过 CSS 访问li
和a
。I don’t think you can select the parent in CSS only.
But as you already seem to have an
.active
class, it would be easier to move that class to theli
(instead of thea
). That way you can access both theli
and thea
via CSS only.您可以使用此脚本:
这将选择文本输入的任何父。但是等等,还有更多。如果需要,可以选择一个指定的父:
或在活动处活动时选择它:
查看此html:
您可以选择
span.help
当input
处于活动状态和显示:还有更多功能;只需查看插件的文档即可。
顺便说一句,它在Internet&nbsp; Explorer中工作。
You can use this script:
This will select any parent of a text input. But wait, there's still much more. If you want, you can select a specified parent:
Or select it when it's active:
Check out this HTML:
You can select that
span.help
when theinput
is active and show it:There are many more capabilities; just check out the documentation of the plugin.
BTW, it works in Internet Explorer.
正如其他几个人所提到的,没有办法仅使用 CSS 来设置元素的父元素的样式,但以下内容适用于 jQuery:
As mentioned by a couple of others, there isn't a way to style an element's parent/s using just CSS but the following works with jQuery:
您可以使用
:has()
伪类(状态:工作草案,规范,MDN,caniuse) 为此:事实上,这个伪类可用于匹配具有特定元素作为子元素、孙子元素、下一个兄弟元素或后续兄弟元素的元素:
我在原始答案中提出的问题仍然相关:
You can use
:has()
pseudo-class (status: working draft, specifications, MDN, caniuse) for this:In fact, this pseudo-class can be used to match an element that has a specific element as child, grand child, next sibling or subsequent sibling:
The concerns I raised in my original answer are still relevant:
伪元素
:focus-within
允许在后代拥有焦点时选择父元素。如果元素具有
tabindex
属性,则该元素可以获得焦点。浏览器支持 focus-within
Tabindex
示例
The pseudo element
:focus-within
allows a parent to be selected if a descendent has focus.An element can be focused if it has a
tabindex
attribute.Browser support for focus-within
Tabindex
Example
在CSS&nbsp; 2中没有办法这样做。您可以将类添加到
li
中,并引用a
:There isn't a way to do this in CSS 2. You could add the class to the
li
and reference thea
:尝试将
a
切换为block
显示,然后使用您想要的任何样式。a
元素将填充li
元素,您将能够根据需要修改其外观。不要忘记将li
padding 设置为 0。Try to switch
a
toblock
display, and then use any style you want. Thea
element will fill theli
element, and you will be able to modify its look as you want. Don't forget to setli
padding to 0.在 CSS Selectors 4 规范中,CSS 引入了一个名为
:has()
的新选择器,它最终让我们可以选择父级。这意味着我们将能够定位一个包含特定子元素的 CSS 元素。 Safari 和 Chrome 105 均已支持此功能。显示了完整的支持表此处。
父选择器的工作原理
在 CSS 中,如果我们想要选择某些内容,我们可以使用沿 DOM 向下排列的选择器。
例如,在 div 标记中选择 ap 标记如下所示:
到目前为止,无法真正选择其中包含
p
标记的div
标记,但是,这意味着我们必须求助于Javascript
。这没有在 CSS 中实现的主要原因是它是一个相当昂贵的操作。 CSS 的解析速度相对较快,但选择父标签需要相对大量的处理。使用
:has
选择器,我们现在可以选择具有p
子元素的div
元素,或者选择器的任何正常组合。例如,选择带有子
p
的div
现在看起来像这样:这将使任何带有子
p
的div
代码>红色。将父级选择与其他选择器相结合
就像任何其他 CSS 选择器一样,我们可以针对特定情况将其结合起来。
例如,如果您只想选择具有直接
span
子级的div
标签:正如
:has
的词汇所建议的那样,它不仅仅是仅限于家长选择。例如,下面我们可以选择一个
span
,其中:has
有一个同级div
:或者甚至选择一个没有子元素的元素,通过使用 :not() 选择器。
例如,下面的代码将选择任何没有 ap 子元素的 div:
选择 CSS 中仅包含文本的元素
CSS 中一个非常常见的问题是
:empty
标签不会选择包含任何内容的元素text - 因此有时一个元素可以包含一个空格,并且:empty
将不适用。:has
选择器使我们能够选择仅包含文本节点且不包含其他子元素的元素。虽然这对于带有空格的简单
:empty
元素来说并不是完美的解决方案(因为这将选择仅包含文本且没有其他 HTML DOM 元素的任何元素),但它确实使我们能够选择带有空格的 DOM 元素只有文本节点,这在以前是不可能的。我们可以通过以下代码来实现这一点:In the CSS Selectors 4 specification, CSS introduces a new selector called
:has()
, which finally lets us select parents. That means is we’ll be able to target a CSS element that has specific children within it. This is already supported in Safari and is also in Chrome 105. The full support table is shownhere.
Parent Selectors workings
In CSS, if we want to select something, we use selectors that descend the DOM.
For example, selecting a p tag within a div tag looks like this:
Until now, couldn’t really select the
div
tags which hadp
tags within them, though, and this meant we had to resort toJavascript
. The main reason this wasn’t implemented in CSS is that it’s quite an expensive operation to do. CSS is relatively fast to parse, but selecting parent tags requires a relatively significantly larger amount of processing.Using the
:has
selector, we can now selectdiv
elements which have ap
children, or any normal combination of selectors.For example, selecting a
div
with a childp
now looks like this:This will make any
div
with a childp
red.Combining parent selection with other selectors
Just like any other CSS selector, we can combine this for specific circumstances.
For example, if you want to select only
div
tags which have directspan
children:As the vocabulary of
:has
suggested, it is not just limited to parent selection.For example, below we can select a
span
which:has
a siblingdiv
:Or even, selecting an element which does not have a child, by using the :not() selector.
For example, the following will select any div which does not have a p child:
Selecting elements that only contain text in CSS
One very common problem in CSS is that the
:empty
tag does not select elements that contain any text - so sometimes an element can contain one space, and:empty
will not apply. The:has
selector gives us the power to select elements that only contain text nodes and no other child elements.Although this is not the perfect solution for simply
:empty
elements with spaces (as this will select any element with just text and no additional HTML DOM elements) - it does give us the ability to select DOM elements with only text nodes, which was not previously possible. We can achieve this with the following code:CSS 选择器“General Sibling Combinator”可能用于什么您想要的:
这与前面有
E
元素的任何F
元素匹配。The CSS selector “General Sibling Combinator” could maybe used for what you want:
This matches any
F
element that is preceded by anE
element.这是选择器级别4 规范的最讨论的方面。这样,选择器将能够使用
:has()
来根据其孩子为元素进行样式。例如:
如果用户徘徊在任何锚点上,将设置红色背景色。
This is the most discussed aspect of the Selectors Level 4 specification. With this, a selector will be able to style an element according to its child by using
:has()
.For example:
will set a red background-color if the user hovers over any anchor.
据我所知,CSS 2 中没有。 CSS 3 具有更强大的选择器,但并非在所有浏览器上一致实现。即使使用改进的选择器,我也不相信它能够完全完成您在示例中指定的内容。
Not in CSS 2 as far as I'm aware. CSS 3 has more robust selectors but is not consistently implemented across all browsers. Even with the improved selectors, I don't believe it will accomplish exactly what you've specified in your example.
我知道OP正在寻找CSS解决方案,但使用jQuery实现很容易。在我的情况下,我需要找到
&lt; ul&gt;
parent tag的parent tag,以适用于&lt; span&gt;
标签,子&lt; li&gt;
。 jQuery具有:has
选择器,因此可以通过其中包含的孩子识别父母:将选择具有
ul
元素,该元素的元素具有ID someid someid < /em>。或回答原始问题,以下问题应该可以解决问题(未经测试):I know the OP was looking for a CSS solution but it is simple to achieve using jQuery. In my case I needed to find the
<ul>
parent tag for a<span>
tag contained in the child<li>
. jQuery has the:has
selector so it's possible to identify a parent by the children it contains:will select the
ul
element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):您可以尝试使用超链接作为父级,然后在悬停时更改内部元素。像这样:
通过这种方式,您可以根据父元素的翻转来更改多个内部标签中的样式。
You might try to use hyperlink as the parent, and then change the inner elements on hover. Like this:
This way you can change the style in multiple inner tags, based on the rollover of the parent element.
这是使用
Pointer-events
的黑客攻击,悬停
:Here's a hack using
pointer-events
withhover
:CSS 父选择器(也称为 :has() 选择器)终于登陆 Safari TP 137。该功能目前也在 Chrome 中实现。 (MDN 文档)
父级选择是通过伪类
完成的:has()
。例如,div:has(> .child)
将选择所有元素,其中子元素具有
child
类。其他示例:
选择元素的直接父元素
选择元素的所有父元素
以下选择器将选择
grandparent
和parent
您还可以将其用于嵌套选择器,甚至与其他伪选择器一起使用类:
其他有效的 CSS 运算符可用于自定义查询。
请密切关注 caniuse.com/css-has 以了解浏览器兼容性。
The CSS parent selector (also know as the :has() selector) has finally landed in Safari TP 137. The feature is currently being implementated in Chrome as well. (MDN Documentation)
Parent selection is done via the pseudo-class
:has()
. For example,div:has(> .child)
will select all<div>
elements with a child having achild
class.Other examples:
Selecting direct parent of an element
Selecting all the parents of an element
The following selector will select both
grandparent
andparent
You can also use it for nested selectors and even with other pseudo classes:
Other valid CSS operators can be used to customize the query.
Keep an eye on caniuse.com/css-has for browser compatibility.
目前没有父选择器和父选择器。它甚至没有在 W3C 的任何讨论中被讨论。您需要了解浏览器如何评估 CSS,才能真正了解我们是否需要它。
这里有很多技术解释。
Jonathan Snook 解释了 CSS 的评估方式。
Chris Coyier 谈论父选择器。
Harry Roberts 再次讲述如何编写高效的 CSS 选择器。
但是 Nicole Sullivan 有一些关于积极趋势的有趣事实。
这些人都是前端开发领域的顶尖人才。
Currently there is no parent selector & it is not even being discussed in any of the talks of W3C. You need to understand how CSS is evaluated by the browser to actually understand if we need it or not.
There is a lot of technical explanation here.
Jonathan Snook explains how CSS is evaluated.
Chris Coyier on the talks of Parent selector.
Harry Roberts again on writing efficient CSS selectors.
But Nicole Sullivan has some interesting facts on positive trends.
These people are all top class in the field of front end development.
只是水平菜单的一个想法...
HTML 的一部分
CSS 的一部分
更新了演示和其余代码
另一个示例如何将其与文本输入一起使用 - 选择父字段集
Just an idea for horizontal menu...
Part of HTML
Part of CSS
Updated demo and the rest of code
Another example how to use it with text-inputs - select parent fieldset
有一个插件扩展了CSS,以包含一些非标准功能,这些功能在设计网站时确实可以提供帮助。称为 eqcss 。
EQCS添加的一件事是父选择器。它可以在所有浏览器,Internet&nbsp; Explorer&nbsp; 8及以上工作。这是格式:
因此,在这里,我们已经在每个元素上打开了一个元素查询
A.Active
,并且对于该查询的样式,$ parent
之类的东西很有意义,因为有一个参考点。浏览器可以找到父,因为它与JavaScript中的parentnode
非常相似。这是
$ parent
和另一个$ parent
demo 在Internet上工作的演示&nbsp; explorer&nbsp; 8 ,以及如果您没有Internet&nbsp; explorer&nbsp; nbsp; 8周围的屏幕截图可与进行测试。eqcss还包括 meta-selectors :
$ prev
for a e元素之前的元素选择的元素和$ this
仅适用于匹配元素查询的元素等等。There's a plugin that extends CSS to include some non-standard features that can really help when designing websites. It's called EQCSS.
One of the things EQCSS adds is a parent selector. It works in all browsers, Internet Explorer 8 and up. Here's the format:
So here we've opened an element query on every element
a.active
, and for the styles inside that query, things like$parent
make sense, because there's a reference point. The browser can find the parent, because it's very similar toparentNode
in JavaScript.Here's a demo of
$parent
and another$parent
demo that works in Internet Explorer 8, as well as a screenshot in case you don't have Internet Explorer 8 around to test with.EQCSS also includes meta-selectors:
$prev
for the element before a selected element and$this
for only those elements that match an element query, and more.现在是2019年, CSS嵌套模块的最新草稿实际上具有这样的东西。引入
@nest
atrules。(从上面的URL复制和粘贴)。
根据此规范的有效选择器的示例:
It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing
@nest
at-rules.(Copy and pasted from the URL above).
Example of valid selectors under this specification:
W3C不包括这样的选择器,因为它会对浏览器产生巨大的性能影响。
The W3C excluded such a selector because of the huge performance impact it would have on a browser.
从技术上讲,没有直接的方法可以做到这一点。不过,您可以使用 jQuery 或 JavaScript 来解决这个问题。
但是,您也可以做这样的事情。
jQuery
如果您想使用 jQuery 实现此目的,这里是 jQuery 父选择器。
Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.
However, you can do something like this as well.
jQuery
If you want to achieve this using jQuery here is the reference for the jQuery parent selector.
简短的答案是 no ;在此阶段,我们在CSS中没有
parent selector
,但是如果您不必交换元素或类,则第二个选项是使用JavaScript。这样的东西:或者,如果您在应用程序中使用 jQuery ,则是一种较短的方法:
The short answer is NO; we don't have a
parent selector
at this stage in CSS, but if you don't have to swap the elements or classes anyway, the second option is using JavaScript. Something like this:Or a shorter way if you use jQuery in your application:
虽然目前标准CSS中没有父选择器,但我正在开发一个名为axe(即增强CSS选择器语法/ ACSSSS)的(个人)项目,其中它的 7 个新选择器,包括:
<
(可实现与>
相反的选择)和^
(可实现与[SPACE]
相反的选择)axe目前处于相对早期的BETA开发阶段。
在这里查看演示:
在上面的示例中,
<
是直接父选择器,因此.child.using-axe < .parent
表示:
您也可以使用:
.child.using-axe
.child.using-axe
.child.using-axe
.child.using-axe
.child.using-axe
.parent
div这意味着:
Although there is no parent selector in standard CSS at present, I am working on a (personal) project called axe (ie. Augmented CSS Selector Syntax / ACSSSS) which, among its 7 new selectors, includes both:
<
(which enables the opposite selection to>
)^
(which enables the opposite selection to[SPACE]
)axe is presently in a relatively early BETA stage of development.
See a demo here:
In the example above
<
is the immediate parent selector, so.child.using-axe < .parent
means:
You could alternatively use:
.child.using-axe < div
which would mean:
编辑2024-10-15
现在有一个
:has()
css功能,除非无法实现所需结果,否则应忽略以下结果!因为内容仅出于历史原因而保留。如果CSS4将一些钩子添加到中,它将很喜欢。在此之前 to break 事物连接的通常方式,这也允许CSS在其正常范围之外运行...
... Pretty Gross ,但是只有CSS和HTML,除了
Body
and:root
从几乎可以通过链接ID
和radio> radio>的属性
/复选框
input
输入 输入 /code> s 和label
触发器;可能有人会在某个时候展示如何重新触发这些。另一个警告是,特定
的特定
id
也许可以使用,第一个复选框
/无线电
wins 换句话说... 但是多个标签都可以指向相同的input
,尽管这会使HTML和CSS看上去甚至更加粗糙。我不确定其他伪类课程,但是我
:检查
for Pre-css&nbsp; 3。如果我没记错的话,那就是[检查]
,这就是为什么您可以在上面的代码中找到它的原因,例如...但是对于
:: efter 和
:悬停
,我完全不确定CSS版本最初出现的哪个版本。这一切都说明了,请不要在生产中使用它,甚至不是愤怒。肯定的是一个笑话,或者换句话说,仅仅因为可以完成的事情并不总是意味着应该。
Edit 2024-10-15
There is now a
:has()
CSS feature and, unless that fails to achieve the desired results, the following should be ignored! Because content remains mainly for historical reasons only.CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use
checkbox
and/orradio
input
s to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the
body
and:root
from just about anywhere by linking theid
andfor
properties ofradio
/checkbox
input
s andlabel
triggers; likely someone'll show how to re-touch those at some point.One additional caveat is that only one
input
of a specificid
maybe used, firstcheckbox
/radio
wins a toggled state in other words... But multiple labels can all point to the sameinput
, though that would make both the HTML and CSS look even grosser.I am not sure about the other pseudo classes, but I
:checked
for pre-CSS 3. If I remember correctly, it was something like[checked]
which is why you may find it in the above code, for example,... but for things like
::after
and:hover
, I'm not at all certain in which CSS version those first appeared.That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.
尝试这个...
该解决方案使用没有JavaScript的普通CSS2规则,并且可以在所有浏览器(新旧)中工作。单击时,儿童
锚
标签会激活其活动
伪级事件。然后,它简单地隐藏自身,允许活动
事件起泡到父li
标签,然后将自己重新安排并以新样式揭示自己的锚点。孩子为父母设计了样式。使用您的示例:
现在,将这些样式与
活动
a
上的伪级应用于链接时 a retyle li 标记链接时,请单击链接:现在应该看到带有绿色背景的链接,现在可以在单击时更改为列表项目的蓝色背景。
转到
单击。
Try this...
This solution uses plain CSS2 rules with no Javascript and works in all browsers, old and new. When clicked, the child
anchor
tag activates itsactive
pseudo-class event. It then simply hides itself, allowing theactive
event to bubble up to the parentli
tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.Using your example:
Now apply these styles with the
active
pseudo-class ona
to restyle the parentli
tag when the link is clicked:You should see the link with a green background now change to the list item's blue background on click.
turns to
on click.
目前,只有当父元素中有
元素时,才能根据子元素更改父元素。当输入获得焦点时,其相应的父元素可能会使用 CSS 受到影响。
以下示例将帮助您了解在 CSS 中使用
:focus-within
。Changing parent element based on child element can currently only happen when we have an
<input>
element inside the parent element. When an input gets focus, its corresponding parent element can get affected using CSS.Following example will help you understand using
:focus-within
in CSS.不,您不能仅在CSS中选择父。
但是,由于您似乎已经拥有一个
Activive
类,因此将该类移动到li
(而不是a
)会更容易。这样,您只能通过CSS访问li
和a
。No, you cannot select the parent in CSS only.
But as you already seem to have an
.active
class, it would be easier to move that class to theli
(instead of thea
). That way you can access both theli
and thea
via CSS only.由于“ CSS工作组先前拒绝父级选择器的建议的主要原因与浏览器性能和增量渲染问题有关”,因此没有CSS(因此在CSS预处理器中)父级选择器。
There no css (and therefore in css preprocessors) parent selector due to "The major reasons for the CSS Working Group previously rejecting proposals for parent selectors are related to browser performance and incremental rendering issues."