是否有 CSS 父选择器? [英] Is there a CSS parent selector?

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

问题描述

如何选择作为锚元素的直接父元素的

  • 元素?

    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 Level 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:

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

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