Is there a CSS parent selector?

ID : 117

viewed : 228

Tags : csscss-selectorscss

Top 5 Answer for Is there a CSS parent selector?

vote vote


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:

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(> { /* 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.

vote vote


Yes: :has()

Browser support: none

vote vote


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.

vote vote


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

vote vote


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:

$("").parents('li').css("property", "value"); 

Top 3 video Explaining Is there a CSS parent selector?