Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a CSS parent selector?

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

Any ideas?

like image 507
jcuenod Avatar asked Jun 18 '09 19:06

jcuenod


People also ask

Is there a parent selector in CSS?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.

Why there is no parent selector in CSS?

There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers. If there was a way to do it, it would be in either of the current CSS selectors specs: Selectors Level 3 Spec.

How do I apply parent child in CSS?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.

Is there a SCSS parent selector?

The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.


2 Answers

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

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

  • Selectors Level 3 Spec
  • CSS 2.1 Selectors Spec

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 */ } 

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

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

like image 107
Dan Herbert Avatar answered Sep 18 '22 15:09

Dan Herbert


Yes: :has()

Browser support: none

like image 41
Yukulélé Avatar answered Sep 22 '22 15:09

Yukulélé