Is there a CSS parent selector?
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.
Yes: :has()
Browser support: none
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 the li
(instead of the a
). That way you can access both the li
and the a
via CSS only.
You can use this script:
*! > input[type=text] { background: #000; }
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:
.input-wrap! > input[type=text] { background: #000; }
Or select it when it's active:
.input-wrap! > input[type=text]:focus { background: #000; }
Check out this HTML:
<div class="input-wrap">
<input type="text" class="Name"/>
<span class="help hide">Your name sir</span>
</div>
You can select that span.help
when the input
is active and show it:
.input-wrap! .help > input[type=text]:focus { display: block; }
There are many more capabilities; just check out the documentation of the plugin.
BTW, it works in Internet Explorer.
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:
$("a.active").parents('li').css("property", "value");