Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

css - 是否有CSS父选择器?(Is there a CSS parent selector?)

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

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

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

(例如,我的CSS将是这样的:)

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.

(显然,可以使用JavaScript进行此操作,但是我希望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).

(我尝试设置样式的菜单已由CMS弹出,因此我无法将active元素移至<li>元素...(除非我将菜单创建模块作为主题,但我不希望这样做) 。)

Any ideas?

(有任何想法吗?)

  ask by jcuenod translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

(如果有办法,可以在当前的CSS选择器规范中使用:)

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

(同时,如果需要选择父元素,则必须使用JavaScript。)


The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation .

(选择器第4级工作草案包括:has()伪类,其工作原理与jQuery实现相同。)

As of 2019, this is still not supported by any browser .

(截至2019年, 任何浏览器仍不支持此功能 。)

Using :has() the original question could be solved with this:

(使用:has()可以用以下方法解决原始问题:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...