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

In 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?

23 upvote
  flag
I wasn't actually borrowing from the jquery docs I was just trying to illustrate the element that I am trying to select. Your suggestion would select the all of the a children of an li tag (see w3.org/TR/CSS2/selector.html) – jcuenod
4 upvote
  flag
More discussion of this problem at //allinonescript.com/questions/45004/… – MatrixFrog
28 upvote
  flag
@Tomas li > a.active selects the child, not the parent. – Stewart
1 upvote
  flag
Interesting to note that the question @MatrixFrog links to this page under "This question already has an answer" ... – Agi Hammerthief
upvote
  flag
@Nigel Nquande: It didn't link here before - in fact, it was asked a year prior. I marked it as a duplicate years after the original comment, mostly because of the canonical answer residing here. – BoltClock
1 upvote
  flag
Are there any updates to this question? I believe the last recorded correspondence on the question was in March 2014. Whats going on with it? – Master Yoda
upvote
  flag
@KyleT: What are you referring to exactly? – BoltClock
upvote
  flag
@BoltClock Is there any talk about whether or not this will happen? This question is from years ago just wondering. – Master Yoda
upvote
  flag
@KyleT: Have you seen the comments under the accepted answer? They basically document the progress that's been made over the years. – BoltClock
upvote
  flag
@BoltClock Yes but the last one is from May last year. Just curious. – Master Yoda
upvote
  flag
@KyleT: Well just keep in mind that these things take time. – BoltClock
upvote
  flag
I hope in the future will be possible to do something like li < a.active, this way will be "consistent" with the already well known syntax li > a.active as the OP wrote. For browser performance concerns I'm pretty sure that evaluate the one or the other will not be a great difference: the browser will evaluate the expression as usual but will pick up the parent instead the child... – willy wonka

26 Answers 11

there isn't a way to do this in css2. you could add the class to the li and reference the a

li.active > a {
    property: value;
}
3 upvote
  flag
by making the a element display:block you can style it to fit the whole of the li area. if you can explain what style you are looking for perhaps I could help with a solution. – Josh
upvote
  flag
this is actually an simple and elegant solution and, in many cases, it makes sense to set the class on the parent. – Ricardo

I've certainly come across instances when it would be handy, but unfortunately parent selectors do not exist in CSS.

Can you explain more about what you're trying to achieve? There might be another way in to a solution, e.g. move the style to the li, then disable it in a.active or via a child selector.

2 upvote
  flag
for ad blocking, to select the facebook post that includes a sponsored label at any number of div levels within the post. – malhal
1 upvote
  flag
This is rather a comment than an answer. – Jost

I don’t think you can select the parent in css only.

But as you already seem to have an .active class, wouldn’t it 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.

4 upvote
  flag
You can't shift the pseudo selector to the list item, as it is not a focusable element. He's using the :active selector, so when the anchor is active he wants the list item to be affected. List items will never be in the active state. As an aside, it's unfortunate that such a selector doesn't exist. Getting a pure CSS menu to be fully keyboard accessible seems to be impossible without it (using sibling selectors you can make submenus created using nested lists to appear, but once the list gains focus it becomes hidden again). If there are any CSS-only solutions to this particular conun – user914183
9 upvote
  flag
@Dominic Aquilina Take a look at the question, the OP is using a class, not a pseudo selector. – jeroen

Not in CSS 2 as far as I'm aware. CSS 3 has more robust selectors but is not consistently implemented across all browsers. Even with the improved selectors, I don't believe it will accomplish exactly what you've specified in your example.

up vote 1836 down vote accepted

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:

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


The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation. As of April 2017, this is still not supported by any browser.

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

li:has(> a.active) { /* styles to apply to the li tag */ }
47 upvote
  flag
It would seem that it has already been suggested and rejected: //allinonescript.com/questions/45004/… – RobM
13 upvote
  flag
Looks like the subject selector has been revisited, except by using a ! now: The subject of the selector can be explicitly identified by appending an exclamation mark (!) to one of the compound selectors in a selector. – animuson
13 upvote
  flag
The prepended $ looked better for me... the appended ! can be overlooked more easily. – Christoph
1 upvote
  flag
@animuson, Christoph: Let's just wait until they've gone through a few more revisions of the draft... – BoltClock
1 upvote
  flag
@animuson I'm in agreement with BoltClock here. The reference I included is the working draft. It has only been changed in the editor's draft version of the spec. Once the new syntax has made its way into the working draft version I'll update my answer. Regardless of the syntax, no browser or JS framework has implemented this yet so the exact syntax isn't very important at the moment. – Dan Herbert
upvote
  flag
Ahhh... with a $ sign I can solve this with CSS 3! – André Pena
3 upvote
  flag
Just as a quickie, the Selectors 4 WD was updated a couple of months ago to include the new syntax. Of course, updating an "old" unusable sample to something that still can't be used anyway would be futile. Besides, they still haven't decided on the final syntax. – BoltClock
upvote
  flag
the '>' selector does not work in chrome or firefox – dopatraman
upvote
  flag
@codeninja The > selector works fine for me in Chrome. Are you sure there isn't something else going wrong? See this test: dabblet.com/gist/5478862 – Dan Herbert
42 upvote
  flag
Major plot twist! The Selectors 4 WD was just updated today to exclude the subject indicator from the fast profile, which is to be used by CSS implementations. If this change remains, it means you won't be able to use the subject indicator in stylesheets anymore (unless you use add some sort of polyfill like the one described in another answer) - you can only use it with the Selectors API and anywhere else that the complete profile may be implemented. – BoltClock
upvote
  flag
@BoltClock: I think I must be missing something, but from the latest spec (to which you've linked) it seems as if we have a subject-selector (yay, finally! And so forth) but we're unable to use it because it's not permitted in the 'fast' selectors; is there a point to this, or just a reserved selector for future use? – David Thomas
1 upvote
  flag
@David Thomas: I see what you mean. The point is that if it is possible to implement the subject indicator for use in selectors, then wherever selectors can be used without affecting the performance of other things (e.g. querySelectorAll(), matches() in selectors-api2), it should be implemented. Also, assuming the spec even allows it - it's not clear right now if it does or if it will - some browsers may even choose to implement the complete profile for CSS, though I suspect it'll be difficult to prove that it can be done in a way that doesn't adversely affect page rendering performance. – BoltClock
3 upvote
  flag
@David Thomas: Most people don't realize this, but the reason why Selectors was made its own module is that while selectors were originally conceived as part of CSS, they're now being used in numerous places other than stylesheets, such as libraries like jQuery and testing frameworks like Selenium. I think the gist of all this is to not let the nature of CSS implementations affect what sort of selectors can be defined for a wider variety of purposes. – BoltClock
2 upvote
  flag
If anyone reading this can give input to the draft, with ! seeming to be the chosen symbol now, how about making a lone ! an alias for !important in CSS attributes too. This way, when thinking in CSS, a ! has the uniform meaning of (something like) "I want this one". Building from this, appending in the selector might be preferable for uniformity, too. With the added advantage of knowing the difference between span!:nth-child(4) (span with 4 children) and span:nth-child(4)! (4th child of span). I hope these ideas can make it into the discussion! – Paul S.
upvote
  flag
@Paul S.: There are several fundamental issues with your proposal. First, since the subject selector might not even be usable in CSS, creating an alias of !important called ! probably isn't going to make a whole lot of sense. Furthermore, you can have more than one !important per property on the same element, but there can only be one subject per selector. – BoltClock
upvote
  flag
@Paul S.: Second, you've misunderstood the selector notation. span:nth-child(4) has only one meaning, and that is "span that is the 4th child". That's because you're attaching the pseudo-class to the element type, which works exactly like attaching an ID or a class to a type selector. Combining simple selectors like this results in a compound selector, which represents one element in a hierarchy, and the spec specifies that ! may only be attached to any one compound selector. – BoltClock
2 upvote
  flag
@Paul S.: If you want to select a span with 4 children, the correct selector would be span! > :nth-child(4), and if you want to select the 4th child of span, that would simply be span > :nth-child(4) (which is already a valid selector today). Each of these has two compound selectors: span, and :nth-child(4), and by default (as it already is with current CSS) the rightmost one is the subject which is what makes the ! optional in the latter case. – BoltClock
1 upvote
  flag
@Simon Pertersen: That's precisely why there hasn't been such a feature in a long time. – BoltClock
upvote
  flag
@BoltClock Great to get the confirmation – Simon Pertersen
39 upvote
  flag
Another major update: it looks like they're considering doing away with the subject selector syntax altogether and replacing it with the :has() pseudo everybody has come to know and love from jQuery. The latest ED has removed all references to the subject indicator, and replaced it with the :has() pseudo. I don't know the exact reasons, but the CSSWG held a poll some time ago and the results must have influenced this decision. It's most likely for compatibility with jQuery (so it can leverage qSA without modifications), and because the subject indicator syntax proved too confusing. – BoltClock
4 upvote
  flag
So, the corresponding selector would be li:has(> a.active). Note that jQuery already supports relative selector syntax in :has(), although it isn't documented anywhere. – BoltClock
1 upvote
  flag
It's a shame, $E elem looks way better, and is easier (faster) to understand then elem:has(E) and is functionally equivalent. – WraithKenny
upvote
  flag
this completely breaks the css foundation: CASCADING style sheets.. – Juan
3 upvote
  flag
its not css4, they need to stop saying css3 too, its just css from here on out. working draft or levels are okay, but the blatant labeling of 'css3' and 'css4' must stop or else everyone is going to start clucking them out like crazy. C-S-S...see? – osirisgothra
4 upvote
  flag
@Juan: This has absolutely nothing to do with cascading. – BoltClock
1 upvote
  flag
@osirisgothra: Yeah, even the official definition of CSS3 is "anything beyond CSS2", which is completely meaningless in practice (and of course there is no "CSS4"). – BoltClock
upvote
  flag
@WraithKenny: It was never actually made clear if it was going to be functionally equivalent. See my answer here for why I think they ultimately went with :has(). – BoltClock
upvote
  flag
@BoltClock I see what you are saying, but I'd prefer the more limited, simple (non-ascending) functionality, and the simpler syntax of the subject selector (selected from the same 'crawl'). I agree that those are two different functionalities, you are right. – WraithKenny
upvote
  flag
@BoltClock thats my point. a "parent" selector in css should never exist, as its not cascading.. css is top down, not bottom up. – Juan
5 upvote
  flag
@Juan That's not what "cascading" means in this context. Cascading has almost nothing to do with selectors. The stylesheets "cascade" in the sense that a { rule1: value; } .foo{ rule2: value2; } results in both rule1 and rule2 having their values set on an a element with a class of foo. The existence of a parent selector has no bearing on that. – Ajedi32
upvote
  flag
@Ajedi32 I know the meaning of cascading. And imo it also applies here. Again, the whole language is based on top down rules, you can't start changing the foundation just because there is a very specific edge case that requires inspecting childrens. But its just my opinion. – Juan
7 upvote
  flag
@Juan Cascading isn't really the limitation for creating a "parent" selector in CSS. There are already sibling selectors, odd/even selectors, and a huge variety of selectors that refer to an element's state/placement that don't have any "top down" pattern. The real limitation is an implementation detail. Browsers have optimized selectors to be parsed forward-only, so any selector that requires backtracking would be inefficient. This is the same reason why there is a "next sibling" selector, but no "previous sibling" selector. – Dan Herbert
1 upvote
  flag
... how can something that's totally unrelated to selectors apply in this context?! How do you go from conflict resolution between two style declarations to matching a parent element in a selector? – BoltClock
upvote
  flag
someone says everything is possible but this ain't – Mahi
upvote
  flag
@Mahi Implementing a parent selector is easy. When you are parsing a stylesheet and you come across a selector that targets it's parent you add that append list if you haven't built the DOM. As you build the DOM and you encounter the element then you can append the styles to the parent element's CSS stylesheet. If are parsing the stylesheet and the DOM is already created you simply add the styles to the parent element stylesheet. I happen to be working in this area so to me it's not that difficult. Just planning ahead. – 1.21 gigawatts
upvote
  flag
When i can use it in Chrome? – Alex78191
upvote
  flag
@Alex78191 Nobody knows. It's not on Chrome's roadmap and the spec may change before any browser implements it. MS Edge has it "under consideration" but it will probably be years before it can be used. – Dan Herbert
upvote
  flag
upvote
  flag
Worth noting that :has() will not be implemented in CSS, at least in the level 4 module. It is explicitly only to be implemented in JS. – jhpratt

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");
20 upvote
  flag
The < selector does not exist (verified using jQuery 1.7.1). – Rob W
5 upvote
  flag
Perhaps that <-syntax worked in 2009 but I've updated it (for 2013). – Alastair
4 upvote
  flag
Even better, use jQuery's built-in :has() selector: $("li:has(a.active)").css("property", "value");. It reads similarly to CSS 4's proposed ! selector. See also: :parent selector, .parents() method, .parent() method. – Rory O'Kane
6 upvote
  flag
And rather than using .css("property", "value") to style the selected elements, you should usually .addClass("someClass") and have in your CSS .someClass { property: value } (via). That way, you can notate the style with the full power of CSS and any preprocessors you are using. – Rory O'Kane

The CSS selector “General Sibling Combinator” could maybe used for what you want:

E ~ F {
    property: value;
}

This matches any F element that is preceded by an E element.

101 upvote
  flag
That's not correct answer, but thanks for reminding us about this selector – Dan
upvote
  flag
This is just sibling selector, it's not child, parent... not really answering the question mate – Alireza

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

3 upvote
  flag
suppose using jquery patent() would be faster. This need testing, however – Dan
2 upvote
  flag
@Idered It fails when you have CSS declaration of a Selector Subject with no child selector (#a! alone throws an error, #a! p works), and so the others will not works either because of Uncaught TypeError: Cannot call method 'split' of undefined: see jsfiddle.net/HerrSerker/VkVPs – HerrSerker
2 upvote
  flag
@HerrSerker I think #a! is an invalid selector, what should it select? – Idered
2 upvote
  flag
@Idered I don't know. The spec doesn't say it is illegal. #a! should select itself. At least their should be no error in the JavaScript – HerrSerker
3 upvote
  flag
Per my comment on the accepted answer, it looks like the polyfill may be required even in the near future after all, because the subject indicator may never be implemented by browsers in CSS. – BoltClock
upvote
  flag
@ldered, I cannot get your example to work. jsfiddle.net/5z5MV – Redtopia
upvote
  flag
@Redtopia It's because you haven't attached the polyfill – Idered
1 upvote
  flag
Can we get a polyfill that doesn't depend on jquery? – Michael
upvote
  flag
upvote
  flag
Isn't the OP asking for a CSS solution? – Dani Springer
upvote
  flag
How would you then stick an :after on that parent? – toddmo

The W3C excluded such a selector because of the huge performance impact it would have on a browser.

19 upvote
  flag
false. because the DOM is a tree, they have to go to the parent before getting to the child, so the simply just go back one node. o.o – NullVoxPopuli
6 upvote
  flag
CSS selectors are a queue so selector order is evaluated rather than the document XPath or DOM hierarchy. – Paul Sweatte
1 upvote
  flag
@rgb At least that's what they told us. – HerrSerker

Try to switch a to block display, and then use any style you want. a element will fill li element and you will be able to modify it's look as you want. Don't forget to set li padding to 0.

li {
  padding: 0;
  overflow: hidden;
}
a {
  display: block;
  width: 100%;
  color: ..., background: ..., border-radius: ..., etc...
}
a.active {
  color: ..., background: ...
}

You might try to use hyperlink as the parent, and then change the inner elements on hover. Like this:

a.active h1 {color:red;}

a.active:hover h1 {color:green;}

a.active h2 {color:blue;}

a.active:hover h1 {color:yellow;}

This way you can change the style in multiple inner tags, based on the rollover of the parent element.

1 upvote
  flag
That is correct, but limits the markup code within the a tag to certain elements only, if you want to conform to XHTML standards. For instance, you cannot use a div within a, without getting a warning of violating the schema. – Ivaylo Slavov
2 upvote
  flag
Totaly right Ivaylo! "a" is a non-block element, so can't use block elements inside it. – riverstorm
1 upvote
  flag
In HTML5 it is perfectly fine to put block elements inside links. – Matthew James Taylor
upvote
  flag
@MatthewJamesTaylor and semantically it is perfectly wrong – Vangel Tzo
1 upvote
  flag
... if it was semantically wrong, they wouldn't have allowed it in HTML5 where it wasn't before. – BoltClock

I know the OP was looking for a CSS solution but it is simple to achieve using jQuery. In my case I needed to find the <ul> parent tag for a <span> tag contained in the child <li>. jQuery has the :has selector so it's possible to identify a parent by the children it contains:

$("ul:has(#someId)")

will select the ul element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):

$("li:has(.active)")
3 upvote
  flag
Or use $yourSpan.closest("ul") and you'll get the parent UL of your span element. Nevertheless your answer is completely offtopic imho. We can answer all of the CSS-taged questions with a jQuery solution. – Robin van Baalen
upvote
  flag
As identified in other answers, there is no way to do this using CSS 2. Given that constraint, the answer I provided is one I know is effective and is the simplest way to answer the question using javascript imho. – David Clarke
upvote
  flag
Given your upvotes, some people agree with you. But the only answer remains the accepted one; plain and simple "it cant be done the way you want it". If the question is how to archieve 60mph on a bicycle and you answer it with "simple; get in a car and hit the gas.", it's still not an answer. Hence my comment. – Robin van Baalen
upvote
  flag
That approach would make SO almost completely useless. I search SO for how to solve problems, not to find the "only answer" doesn't address the issue. That is why SO is so awesome, because there is always more than one way to skin a cat. – David Clarke

There is no parent selector; just the way there is no previous sibling selector. One good reason for not having these selectors is because the browser has to traverse through all children of an element to determine whether or not a class should be applied. For example if you wrote:

body:contains-selector(a.active) { background: red; }

Then the browser will have to wait until it has loaded and parsed everything until the </body> to determine if the page should be red or not.

This article Why we don't have a parent selector explains it in detail.

8 upvote
  flag
so make the browser faster. the internet itself faster. this selector is definitely needed, and the reason for not implementing it is, sadly, because we live in a slow, primitive world. – vsync
6 upvote
  flag
actually, the selector would make a very fast browser look slow. – Salman A
7 upvote
  flag
I am sure humanity will find a way to deal with this in the next 10 years..eventually. – vsync
1 upvote
  flag
I was just reading about a new startup by Elon Musk to solve this exact problem! – xdhmoore

Currently there is no parent selector & it is not even being discussed in any of the talks of W3C. You need to understand how CSS is evaluated by the browser to actually understand if we need it or not.

There is a lot of technical explanation here.

Jonathan Snook explains how CSS is evaluated.

Chris Coyier on the talks of Parent selector.

Harry Roberts again on writing efficient CSS selectors.

But Nicole Sullivan has some interesting facts on positive trends.

These people are all top class in the field of front end development.

7 upvote
  flag
The need is defined by web developers' requirements, whether to have it in the spec is decided by other factors. – nicodemus13

This is the most discussed aspect of the Selectors Level 4 specification. With this selector will be able to style an element according to its child by using an exclamation mark after the given selector (!).

For example:

body! a:hover{
   background: red;
}

will set a red background-color if the user hovers over any anchor.

But we have to wait browsers implementation :(

4 upvote
  flag
Sadly, but now this feature is out of specification as I know... – Qwertiy

Technically there is no direct way to do this however, you can sort that with either jquery or javascript.

Howeve,r you can do something like this as well.

a.active h1 {color:blue;}
a.active p {color: green;}

jQuery

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

If you want to achieve this using jQuery here is the reference for jQuery parent selector

Has somebody suggested something like this? Just an idea for horizontal menu...

part of HTML

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

part of CSS

/* hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

Updated demo and the rest of code

Another example how to use it with text-inputs - select parent fieldset

1 upvote
  flag
It's not at all clear to me how you mean to generalize this to some/many/most of the parent selector use cases, or even exactly which parts of this CSS are doing what. Can you add a thorough explanation? – Nathan Tuggy
1 upvote
  flag
I did not try to apply this to real world scenarios, that is why I say "Not for production". But I think It can be applied to 2-level menu only with fixed item width. "which parts of this CSS are doing what" - .test-sibling here is actually background of parent item (the last line of CSS). – Ilya B.
1 upvote
  flag
Added explanation (css section of jsfiddle, starting from "MAIN PART")... And I was mistaken - there may be any number of sublevels. – Ilya B.

No you cannot select the parent in css only.

But as you already seem to have an .active class, wouldn´t it 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.

upvote
  flag
The problem is that a CMS is generating the markup – jcuenod

Just as easy help for whom are trying to get rid of this lack of parent selector: the most simple thing are two lines of jQuery.

Let's figure out the situation in which we want to change the class of the <form> element basing on the validation of hinner inputs:

HTML:

<div class="parent-row">
    <label>Form 1</label>
    <input type="text"  name="field1" />
    <input type="text" class="validation-error" name="field2" />
    <input type="text" name="field3" />
</div>

CSS:

.make-red {
    color:red
}

JQuery:

if($( "input" ).hasClass( "validation-error" )) {
     $( ".parent-row" ).addClass( "make-red" );
}

http://jsfiddle.net/9c3hrn9y/3/

5 upvote
  flag
The question acknowledges "Obviously there are ways of doing this with JavaScript" but looks for a pure CSS way if it exists. – Nathan Tuggy
upvote
  flag
I added this answer for someone who was looking for a solution (not necessary CSS) and whose question has been closed referring to this one. Anyway, thanks for the downvote. – holden
upvote
  flag

There's a plugin that extends CSS to include some non-standard features that can really help when designing websites. It's called EQCSS.

One of the things EQCSS adds is a parent selector. It works in all browsers IE8 and up. Here's the format:

@element 'a.active' {
  $parent {
    background: red;
  }
}

So here we've opened an element query on every element a.active, and for the styles inside that query, things like $parent make sense because there's a reference point. The browser can find the parent, because it's very similar to parentNode in JavaScript.

Here's a demo of $parent and another $parent demo that works in IE8, as well as a screenshot in case you don't have IE8 around to test with.

EQCSS also includes meta-selectors $prev for the element before a selected element, $this for only those elements that match an element query, and more.

In CSS, we can cascade to the properties down the hierarchy but not in the oppostite direction. To modify the parent style on child event, probably use jQuery.

$el.closest('.parent').css('prop','value');

Although there is no parent selector in standard CSS at present, I am working on a (personal) project called axe (ie. Augmented CSS Selector Syntax / ACSSSS) which, among its 7 new selectors, includes both:

  1. an immediate parent selector < (which enables the opposite selection to >)
  2. an any ancestor selector ^ (which enables the opposite selection to [SPACE])

axe is presently in a relatively early BETA stage of development.

See a demo here:

http://rounin.co.uk/projects/axe/axe2.html

(compare the two lists on the left styled with standard selectors and the two lists on the right styled with axe selectors)

1 upvote
  flag
The project is in an early Beta stage at present. You can (at least currently) activate axe selectors in your CSS styles by including <script src="https://rouninmedia.github.io/axe/axe.js"></script> at the very end of your html document, just before </body>. – Rounin

Short answer is NO, we don't have a parent selector at this stage in CSS, but if you don't have anyway to swap the elements or classes, the second option is using JavaScript, something like this:

var activeATag = Array.prototype.slice.call(document.querySelectorAll('a.active'));

activeATag.map(function(x) {
  if(x.parentNode.tagName === 'LI') {
    x.parentNode.style.color = 'red'; //your property: value;
  }
});

or a Shorter way if you use jQuery in your application:

$('a.active').parents('li').css('color', 'red'); //your property: value;

It´s possible with ampersand in SASS:

h3
  font-size: 20px
  margin-bottom: 10px
  .some-parent-selector &
    font-size: 24px
    margin-bottom: 20px

CSS output:

h3 {
  font-size: 20px;
  margin-bottom: 10px;
}
.some-parent-selector h3 {
  font-size: 24px;
  margin-bottom: 20px;
}
upvote
  flag
it's true, but only if you know the selector in advance. – Shahar

The pseudoelement :focus-within allows a parent to be selected if a descendent has focus.

An element can be focused if it has a tabindex attribute.

Browser support for focus-within

Tabindex

Example

.click {
  cursor: pointer;
}

.color:focus-within .change {
  color: red;
}

.color:focus-within p {
  outline: 0;
}
<div class="color">
  <p class="change" tabindex="0">
    I will change color
  </p>
  <p class="click" tabindex="1">
    Click me
  </p>
</div>

yes: :has()

browser support: none

Not the answer you're looking for? Browse other questions tagged or ask your own question.