3490

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?

TylerH
  • 19,065
  • 49
  • 65
  • 86
jcuenod
  • 48,573
  • 13
  • 58
  • 98

31 Answers31

2812

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

Boris
  • 7,044
  • 6
  • 62
  • 63
Dan Herbert
  • 90,244
  • 46
  • 174
  • 217
  • 75
    It would seem that it has already been suggested and rejected: http://stackoverflow.com/questions/45004/complex-css-selector-for-parent-of-active-child/45530#45530 – RobM Oct 27 '10 at 12:22
  • 18
    Looks like the [subject selector](http://dev.w3.org/csswg/selectors4/#subject) 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 Jan 29 '12 at 21:30
  • 16
    The prepended `$` looked better for me... the appended `!` can be overlooked more easily. – Christoph Feb 13 '12 at 11:25
  • 1
    @animuson, Christoph: Let's just wait until they've gone through a few more revisions of the draft... – BoltClock Feb 20 '12 at 17:15
  • 1
    @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 Feb 20 '12 at 18:08
  • 3
    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 Oct 23 '12 at 15:11
  • @codeninja The `>` selector works fine for me in Chrome. Are you sure there isn't something else going wrong? See this test: http://dabblet.com/gist/5478862 – Dan Herbert Apr 28 '13 at 23:27
  • 53
    Major plot twist! The Selectors 4 WD was just updated [today](http://www.w3.org/TR/2013/WD-selectors4-20130502) 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](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector/7049832#7049832)) - you can only use it with the Selectors API and anywhere else that the complete profile may be implemented. – BoltClock May 02 '13 at 15:19
  • @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 says reinstate Monica May 05 '13 at 18:27
  • 1
    @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 May 06 '13 at 06:24
  • 3
    @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 May 06 '13 at 06:35
  • 2
    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. Nov 13 '13 at 13:25
  • @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 Dec 18 '13 at 09:58
  • @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 Dec 18 '13 at 10:00
  • 2
    @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 Dec 18 '13 at 10:05
  • 61
    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 May 04 '14 at 14:28
  • 4
    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 May 04 '14 at 14:30
  • 1
    It's a shame, `$E elem` looks way better, and is easier (faster) to understand then `elem:has(E)` and is functionally equivalent. – WraithKenny Oct 10 '14 at 19:22
  • 3
    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 Nov 28 '14 at 12:50
  • 4
    @Juan: This has absolutely nothing to do with cascading. – BoltClock Jan 20 '15 at 19:27
  • 2
    @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 Jan 20 '15 at 19:28
  • @WraithKenny: It was never actually made clear if it was going to be functionally equivalent. See my answer [here](http://stackoverflow.com/questions/27982922/latest-on-css-parent-selector/27983098#27983098) for why I think they ultimately went with `:has()`. – BoltClock Jan 20 '15 at 19:30
  • @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 Jan 28 '15 at 02:30
  • @BoltClock thats my point. a "parent" selector in css should never exist, as its not cascading.. css is top down, not bottom up. – Juan Feb 19 '15 at 04:40
  • 6
    @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 Oct 27 '15 at 18:52
  • @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 Oct 28 '15 at 19:53
  • 10
    @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 Oct 29 '15 at 20:38
  • 1
    ... 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 Nov 03 '15 at 17:11
  • @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 Jun 15 '17 at 17:19
  • When i can use it in Chrome? – Alex78191 Jun 19 '17 at 00:17
  • @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 Jul 10 '17 at 19:17
  • 1
    [Edge is the only one considering adding `:has()`](http://caniuse.com/#feat=css-has). Please upvote it [here](https://wpdev.uservoice.com/forums/257854-microsoft-edge-developer/suggestions/8977591--has). – wha7ever Oct 02 '17 at 16:47
  • 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 Dec 13 '17 at 22:29
  • @jhpratt The world would be a very different place if browser vendors adhered strictly to the W3C's CSS specs. – TylerH May 08 '18 at 19:42
  • @TylerH For one, it's the CSSWG that creates specs. Regardless, the people writing specs are (for the most part) representatives of vendors. Specifically regarding the `:has()` selector or any other parent selector, implementation would fundamentally change the single-pass nature of CSS, which I don't expect to happen anytime soon. That's coming from someone who follows the WG's discussions relatively closely. – jhpratt May 08 '18 at 21:35
  • 2
    @jhpratt You are preaching to the choir, buddy. I am aware of how the working groups operate and write specs, having worked with them and advocated for :has() (among many other things) for years. – TylerH May 09 '18 at 13:51
  • ``:has()`` still isn't a quality parent selector since technically you couldn't select a child without knowing who the parent was. Unless you could ``*:has()``. – Grant Noe May 22 '19 at 23:48
  • @GrantNoe You can. In addition, using `#myDiv:has(.class)` gets all descendant elements with .class, not just elements where myDiv is the parent. – mbomb007 Aug 02 '19 at 13:59
  • end of 2019 `document.querySelectorAll('li:has(> a.active)')` gives me `Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'li:has(> a.active)' is not a valid selector.` – Toolkit Nov 16 '19 at 05:13
171

Yes: :has()

Browser support: none

Yukulélé
  • 11,464
  • 8
  • 52
  • 76
  • 1
    As @Rodolfo Jorge Nemer Nogueira pointed out, it is possible with sass (scss) by using the & sign. That then gets compiled to the desired css. It would be nice if the next css version supported – TamusJRoyce Aug 05 '20 at 11:48
  • 14
    `CSS:has(':has') == false` – Andrew Aug 11 '20 at 20:01
  • 9
    `CSS:has(':has') === false` – xdhmoore Oct 23 '20 at 04:57
  • 2
    Andrew & @xdhmoore can you explain? – Yukulélé Oct 23 '20 at 08:26
  • 4
    @Yukulélé Sorry a bit of a joke. Andrew's comment is sort of a pun with the word 'has' as if it was a CSS operator saying whether or not CSS "has" a certain feature. In this case CSS does not have the `:has` selector so `CSS::has(':has')` is false. My comment refers to the fact that it's common for people in JavaScript to [recommend use of the `===` operator over the `==`](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons). – xdhmoore Oct 23 '20 at 21:36
  • 2
    Actually, I think there is [experimental syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) equivalent to Andrew's statement: `@supports selector(:has(a))` – xdhmoore Oct 23 '20 at 21:38
  • 3
    Well this is useful – Jiminy Cricket Jan 13 '21 at 03:55
168

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jeroen
  • 88,615
  • 21
  • 107
  • 128
  • 4
    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 –  Aug 26 '11 at 13:46
  • 14
    @Dominic Aquilina Take a look at the question, the OP is using a class, not a pseudo selector. – jeroen Aug 26 '11 at 14:34
138

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Idered
  • 1,885
  • 1
  • 17
  • 19
  • 5
    suppose using jquery `patent()` would be faster. This need testing, however – Dan Sep 22 '11 at 19:30
  • 2
    @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 http://jsfiddle.net/HerrSerker/VkVPs/ – yunzen Apr 16 '13 at 15:33
  • 3
    @HerrSerker I think #a! is an invalid selector, what should it select? – Idered Apr 17 '13 at 13:41
  • 2
    @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 – yunzen Apr 17 '13 at 15:31
  • 5
    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 May 02 '13 at 15:35
  • How would you then stick an `:after` on that parent? – toddmo May 01 '17 at 19:54
  • 1
    Please add the contents of the script here, otherwise this is useless when GitHub is down. – TylerH Jun 06 '18 at 13:42
114

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");
Alastair
  • 6,451
  • 3
  • 33
  • 29
zcrar70
  • 2,996
  • 2
  • 21
  • 18
  • 22
  • 6
    Perhaps that ` – Alastair May 02 '13 at 05:10
  • 5
    Even better, use jQuery's built-in [`:has()` selector](http://api.jquery.com/has-selector/): `$("li:has(a.active)").css("property", "value");`. It reads similarly to CSS 4's proposed `!` selector. See also: [`:parent` selector](http://api.jquery.com/parent-selector/), [`.parents()` method](http://api.jquery.com/parents/), [`.parent()` method](http://api.jquery.com/parent/). – Rory O'Kane May 08 '13 at 22:12
  • 7
    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](http://stackoverflow.com/a/6279001/578288)). That way, you can notate the style with the full power of CSS and any preprocessors you are using. – Rory O'Kane May 08 '13 at 22:20
77

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.

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Salman A
  • 229,425
  • 77
  • 398
  • 489
  • 12
    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 Feb 19 '14 at 21:33
  • 13
    actually, the selector would make a very fast browser look slow. – Salman A Feb 20 '14 at 04:09
  • 7
    I trust that browser developers would come up with an implementation which is (at least) as fast as the javascript version, which is the one people end up using anyway. – Marc.2377 Jun 09 '18 at 00:15
  • "we live in a slow, primitive world" *cough cough* new apple watch *cough cough* – Marvin May 05 '19 at 19:26
  • 1
    @Marc.2377 If you try the above example in JS on your website, I'm never going to visit it. On the other side, I'd say that most of the time, you only care about immediate children, so if it was only limited to the immediate children, it'd be a good addition without too much impact. – xryl669 Sep 07 '19 at 12:41
61

There isn't a way to do this in CSS 2. You could add the class to the li and reference the a:

li.active > a {
    property: value;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Josh
  • 5,998
  • 1
  • 31
  • 54
  • 3
    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 Jun 18 '09 at 21:53
  • this is actually an simple and elegant solution and, in many cases, it makes sense to set the class on the parent. – Ricardo Mar 18 '16 at 23:17
37

Try to switch a to block display, and then use any style you want. The a element will fill the li element, and you will be able to modify its 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: ...
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Raseko
  • 379
  • 3
  • 3
31

The pseudo element :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>
roberrrt-s
  • 7,249
  • 2
  • 41
  • 53
sol
  • 19,364
  • 5
  • 33
  • 48
  • 2
    This works fine in my case, thanks! Just a not, the example would be more ilustrative if you change the color to the parent, not to the sibling, this is replace `.color:focus-within .change` with `.color:focus-within`. In my case i'm using bootstrap nav-bar that add the class to the children when active and I want to add a class to the parent .nav-bar. I think this is a pretty common scenario where I own the markup but the component css+js is bootstrap (or other) so I cannot change the behavior. Although I can add tabindex and use this css. Thanks! – cancerbero Jun 29 '18 at 15:13
28

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.

Cody Gray
  • 222,280
  • 47
  • 466
  • 543
cobaasta
  • 577
  • 4
  • 2
26

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.

Mark Hurd
  • 12,528
  • 2
  • 24
  • 28
23

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)")
David Clarke
  • 12,002
  • 8
  • 80
  • 105
  • 3
    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 Jul 18 '13 at 17:40
  • 1
    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 Dec 19 '15 at 19:27
  • 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 Dec 19 '15 at 19:36
  • 1
    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 Dec 20 '15 at 18:35
23

This is the most discussed aspect of the Selectors Level 4 specification. With this, a 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 for browsers' implementation :(

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Marco Allori
  • 2,874
  • 29
  • 24
23

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.

TylerH
  • 19,065
  • 49
  • 65
  • 86
riverstorm
  • 520
  • 4
  • 8
  • 1
    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 Jul 24 '12 at 18:22
  • 2
    Totaly right Ivaylo! "a" is a non-block element, so can't use block elements inside it. – riverstorm Dec 12 '12 at 22:34
  • 1
    In HTML5 it is perfectly fine to put block elements inside links. – Matthew James Taylor Apr 06 '14 at 07:47
  • 2
    ... if it was semantically wrong, they wouldn't have allowed it in HTML5 where it wasn't before. – BoltClock Dec 28 '15 at 15:54
19

Here's a hack using pointer-events with hover:

<!doctype html>
<html>
    <head>
        <title></title>
        <style>
/* accessory */
.parent {
    width: 200px;
    height: 200px;
    background: gray;
}
.parent, 
.selector {
    display: flex;
    justify-content: center;
    align-items: center;
}
.selector {
    cursor: pointer;
    background: silver;
    width: 50%;
    height: 50%;
}
        </style>
        <style>
/* pertinent */
.parent {
    background: gray;
    pointer-events: none;
}
.parent:hover {
    background: fuchsia;
}
.parent 
.selector {
    pointer-events: auto;
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="selector"></div>
        </div>
    </body>
</html>
Jan Kyu Peblik
  • 1,140
  • 11
  • 17
15

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

Community
  • 1
  • 1
Ilya B.
  • 900
  • 7
  • 13
  • 3
    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 Oct 28 '15 at 07:57
  • 2
    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. Oct 28 '15 at 08:08
  • 2
    Added explanation (css section of jsfiddle, starting from "MAIN PART")... And I was mistaken - there may be any number of sublevels. – Ilya B. Oct 28 '15 at 12:59
14

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.

Nathan Tuggy
  • 2,239
  • 27
  • 28
  • 36
Suraj Naik
  • 503
  • 4
  • 7
  • 12
    The `need` is defined by web developers' requirements, whether to have it in the spec is decided by other factors. – nicodemus13 May 15 '14 at 09:04
14

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, Internet Explorer 8 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 Internet Explorer 8, as well as a screenshot in case you don't have Internet Explorer 8 around to test with.

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
innovati
  • 519
  • 1
  • 7
  • 12
12

It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing @nest at-rules.

3.2. The Nesting At-Rule: @nest

While direct nesting looks nice, it is somewhat fragile. Some valid nesting selectors, like .foo &, are disallowed, and editing the selector in certain ways can make the rule invalid unexpectedly. As well, some people find the nesting challenging to distinguish visually from the surrounding declarations.

To aid in all these issues, this specification defines the @nest rule, which imposes fewer restrictions on how to validly nest style rules. Its syntax is:

@nest = @nest <selector> { <declaration-list> }

The @nest rule functions identically to a style rule: it starts with a selector, and contains declarations that apply to the elements the selector matches. The only difference is that the selector used in a @nest rule must be nest-containing, which means it contains a nesting selector in it somewhere. A list of selectors is nest-containing if all of its individual complex selectors are nest-containing.

(Copy and pasted from the URL above).

Example of valid selectors under this specification:

.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .foo > .bar { color: blue; }
 */

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .parent .foo { color: blue; }
 */

.foo {
  color: red;
  @nest :not(&) {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   :not(.foo) { color: blue; }
 */
Community
  • 1
  • 1
roberrrt-s
  • 7,249
  • 2
  • 41
  • 53
11

Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.

However, 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 the jQuery parent selector.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Prabhakar Undurthi
  • 5,818
  • 2
  • 36
  • 46
11

The short answer is NO; we don't have a parent selector at this stage in CSS, but if you don't have to swap the elements or classes anyway, 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;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alireza
  • 83,698
  • 19
  • 241
  • 152
10

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

rgb
  • 1,108
  • 1
  • 9
  • 14
  • 28
    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 Nov 10 '11 at 16:56
  • 9
    CSS selectors are a [queue](http://www.snook.ca/archives/html_and_css/css-parent-selectors) so [selector order](http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/) is evaluated rather than the document XPath or DOM hierarchy. – Paul Sweatte Aug 18 '12 at 16:14
  • 4
    @rgb At least that's what they told us. – yunzen Apr 16 '13 at 15:35
7

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:

.parent {
  float: left;
  width: 180px;
  height: 180px;
  margin-right: 12px;
  background-color: rgb(191, 191, 191);
}

.child {
  width: 90px;
  height: 90px;
  margin: 45px;
  background-color: rgb(255, 255, 0);
}

.child.using-axe < .parent {
  background-color: rgb(255, 0, 0);
}
<div class="parent">
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child using-axe"></div>
</div>


<script src="https://rouninmedia.github.io/axe/axe.js"></script>

In the example above < is the immediate parent selector, so

  • .child.using-axe < .parent

means:

any immediate parent of .child.using-axe which is .parent

You could alternatively use:

  • .child.using-axe < div

which would mean:

any immediate parent of .child.using-axe which is a div

Rounin
  • 21,349
  • 4
  • 53
  • 69
  • 3
    The project is in an early Beta stage at present. You can (at least currently) activate axe selectors in your CSS styles by including `` at the very end of your html document, just before `

    `.

    – Rounin Jul 12 '17 at 16:40
7

Any ideas?

CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use checkbox and/or radio inputs to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...

/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
  display: none;
  visibility: hidden;
  opacity: 0;
  filter: alpha(opacity=0); /* Old Microsoft opacity */
}


/* Base style for content and style menu */
.main__content {
  background-color: lightgray;
  color: black;
}

.menu__hidden {
  background-color: black;
  color: lightgray;
  /* Make list look not so _listy_ */
  list-style: none;
  padding-left: 5px;
}

.menu__option {
  box-sizing: content-box;
  display: block;
  position: static;
  z-index: auto;
}

/* &#9660; - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
  content: '\2630';
  display: inline-block;
}
*/

/* &#9660; - Down Arrow */
.menu__trigger__selection::after {
  content: "\25BC";
  display: inline-block;
  transform: rotate(90deg);
}


/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
  cursor: pointer;
  background-color: darkgray;
  color: white;
}


/**
 * Things to do when checkboxes/radios are checked
 */

.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
  transform: rotate(0deg);
}

/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
  display: block;
  visibility: visible;
  opacity: 1;
  filter: alpha(opacity=100); /* Microsoft!? */
}


/**
 * Hacky CSS only changes based off non-inline checkboxes
 * ... AKA the stuff you cannot unsee after this...
 */
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
  background-color: lightgray;
  color: black;
}

.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
  background-color: black;
  color: lightgray;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
  background-color: darkgreen;
  color: red;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
  color: darkorange;
}
<!--
  This bit works, but will one day cause troubles,
  but truth is you can stick checkbox/radio inputs
  just about anywhere and then call them by id with
  a `for` label. Keep scrolling to see what I mean
-->
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-default">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-one">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-two">


<div class="main__content">

  <p class="paragraph__split">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  </p>

  <input type="checkbox"
         class="menu__checkbox__selection"
         id="trigger-style-menu">
  <label for="trigger-style-menu"
         class="menu__trigger__selection"> Theme</label>

  <ul class="menu__hidden">
    <li class="menu__option">
      <label for="style-default"
             class="menu__trigger__style">Default Style</label>
    </li>

    <li class="menu__option">
      <label for="style-one"
             class="menu__trigger__style">First Alternative Style</label>
    </li>

    <li class="menu__option">
      <label for="style-two"
             class="menu__trigger__style">Second Alternative Style</label>
    </li>
  </ul>

  <p class="paragraph__split">
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</div>

... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the body and :root from just about anywhere by linking the id and for properties of radio/checkbox inputs and label triggers; likely someone'll show how to re-touch those at some point.

One additional caveat is that only one input of a specific id maybe used, first checkbox/radio wins a toggled state in other words... But multiple labels can all point to the same input, though that would make both the HTML and CSS look even grosser.


... I'm hoping that there is some sort of workaround that exists native to CSS Level 2...

I am not sure about the other pseudo classes, but I :checked for pre-CSS 3. If I remember correctly, it was something like [checked] which is why you may find it in the above code, for example,

.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
 /* rules: and-stuff; */
}

... but for things like ::after and :hover, I'm not at all certain in which CSS version those first appeared.

That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.

S0AndS0
  • 746
  • 1
  • 6
  • 18
5

At least up to and including CSS 3 you cannot select like that. But it can be done pretty easily nowadays in JavaScript, you just need to add a bit of vanilla JavaScript, notice that the code is pretty short.

cells = document.querySelectorAll('div');
[].forEach.call(cells, function (el) {
    //console.log(el.nodeName)
    if (el.hasChildNodes() && el.firstChild.nodeName=="A") {
        console.log(el)
    };
});
<div>Peter</div>
<div><a href="#">Jackson link</a></div>
<div>Philip</div>
<div><a href="#">Pullman link</a></div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eduard Florinescu
  • 13,721
  • 26
  • 101
  • 164
4

No, you cannot 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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaurav Aggarwal
  • 8,921
  • 5
  • 27
  • 65
4

There no css (and therefore in css preprocessors) parent selector due to "The major reasons for the CSS Working Group previously rejecting proposals for parent selectors are related to browser performance and incremental rendering issues."

Dmitry Sokolov
  • 865
  • 9
  • 20
2

I'd hire some JavaScript code to do that. For example, in React when you iterate over an array, add another class to the parent component, which indicates it contains your children:

<div className={`parent ${hasKiddos ? 'has-kiddos' : ''}`}>
    {kiddos.map(kid => <div key={kid.id} />)}
</div>

And then simply:

.parent {
    color: #000;
}

.parent.has-kiddos {
    color: red;
}
Damiano
  • 942
  • 2
  • 10
  • 22
2

Changing parent element based on child element can currently only happen when we have an <input> element inside the parent element. When an input gets focus, its corresponding parent element can get affected using CSS.

Following example will help you understand using :focus-within in CSS.

.outer-div {
  width: 400px;
  height: 400px;
  padding: 50px;
  float: left
}

.outer-div:focus-within {
  background: red;
}

.inner-div {
  width: 200px;
  height: 200px;
  float: left;
  background: yellow;
  padding: 50px;
}
<div class="outer-div">
  <div class="inner-div">
    I want to change outer-div(Background color) class based on inner-div. Is it possible?
    <input type="text" placeholder="Name" />
  </div>
</div>
VFDan
  • 802
  • 8
  • 22
Sethuraman
  • 598
  • 5
  • 14
2

Try this...

This solution uses plain CSS2 rules with no Javascript and works in all browsers, old and new. When clicked, the child anchor tag activates its active pseudo-class event. It then simply hides itself, allowing the active event to bubble up to the parent li tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.

Using your example:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

Now apply these styles with the active pseudo-class on a to restyle the parent li tag when the link is clicked:

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

You should see the link with a green background now change to the list item's blue background on click.

enter image description here

turns to

enter image description here

on click.

Stokely
  • 4,231
  • 1
  • 14
  • 10
-1

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');