有 CSS 父选择器吗?

Is there a CSS parent selector?(有 CSS 父选择器吗?)

本文介绍了有 CSS 父选择器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择作为锚元素直接父级的 <li> 元素?

How do I select the <li> element that is a direct parent of the anchor element?

例如,我的 CSS 是这样的:

As an example, my CSS would be something like this:

li < a.active {
    property: value;
}

显然有一些使用 JavaScript 的方法,但我希望有某种解决方法存在于 CSS 级别 2 中.

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.

我试图设置样式的菜单被 CMS 吐出,所以我无法将活动元素移动到 <li> 元素...(除非我为我不想做的菜单创建模块).

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).

有什么想法吗?

推荐答案

目前无法在 CSS 中选择元素的父级.

There is currently no way to select the parent of an element in CSS.

如果有办法做到这一点,它会在当前的 CSS 选择器规范中:

If there was a way to do it, it would be in either of the current CSS selectors specs:

  • 选择器 3 级规范
  • CSS 2.1 选择器规范

也就是说,Selectors Level 4 Working Draft 包括一个:has() 将提供此功能的伪类.它将类似于 jQuery 实现.

That said, the Selectors Level 4 Working Draft includes a :has() pseudo-class that will provide this capability. It will be similar to the jQuery implementation.

li:has(> a.active) { /* styles to apply to the li tag */ }

但是,截至 2021 年,任何浏览器仍然不支持.

However, as of 2021, this is still not supported by any browser.

与此同时,如果您需要选择父元素,则必须使用 JavaScript.

In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

这篇关于有 CSS 父选择器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:有 CSS 父选择器吗?

基础教程推荐