By jcuenod


2009-06-18 19:59:36 8 Comments

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?

27 comments

@Roberrrt 2019-03-19 14:14:57

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

@Rodolfo Jorge Nemer Nogueira 2017-08-03 18:19:03

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;
}

@Shahar 2017-08-09 08:02:11

it's true, but only if you know the selector in advance.

@Jacob Ford 2019-03-25 12:41:09

This does not select h3's parent, which was the goal. This would select h3s which are descendants of .some-parent-selector.

@Jan Kyu Peblik 2018-07-31 22:47:03

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>

@Dan Herbert 2009-06-18 20:16:50

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

@RobM 2010-10-27 12:22:32

It would seem that it has already been suggested and rejected: stackoverflow.com/questions/45004/…

@animuson 2012-01-29 21:30:46

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.

@Christoph 2012-02-13 11:25:52

The prepended $ looked better for me... the appended ! can be overlooked more easily.

@BoltClock 2012-02-20 17:15:45

@animuson, Christoph: Let's just wait until they've gone through a few more revisions of the draft...

@Dan Herbert 2012-02-20 18:08:33

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

@André Pena 2012-04-10 16:53:27

Ahhh... with a $ sign I can solve this with CSS 3!

@BoltClock 2012-10-23 15:11:20

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.

@dopatraman 2013-04-28 19:35:02

the '>' selector does not work in chrome or firefox

@Dan Herbert 2013-04-28 23:27:15

@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

@BoltClock 2013-05-02 15:19:51

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.

@David Thomas 2013-05-05 18:27:28

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

@BoltClock 2013-05-06 06:24:48

@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 2013-05-06 06:35:49

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

@Paul S. 2013-11-13 13:25:54

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!

@BoltClock 2013-12-18 09:58:57

@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 2013-12-18 10:00:01

@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 2013-12-18 10:05:43

@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 2014-05-04 14:28:10

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 2014-05-04 14:30:06

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.

@WraithKenny 2014-10-10 19:22:34

It's a shame, $E elem looks way better, and is easier (faster) to understand then elem:has(E) and is functionally equivalent.

@Juan 2014-10-22 23:33:40

this completely breaks the css foundation: CASCADING style sheets..

@osirisgothra 2014-11-28 12:50:11

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?

@BoltClock 2015-01-20 19:27:02

@Juan: This has absolutely nothing to do with cascading.

@BoltClock 2015-01-20 19:28:26

@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 2015-01-20 19:30:17

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

@WraithKenny 2015-01-28 02:30:25

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

@Juan 2015-02-19 04:40:26

@BoltClock thats my point. a "parent" selector in css should never exist, as its not cascading.. css is top down, not bottom up.

@Ajedi32 2015-10-27 18:52:15

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

@Juan 2015-10-28 19:53:22

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

@Dan Herbert 2015-10-29 20:38:38

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

@BoltClock 2015-11-03 17:11:55

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

@1.21 gigawatts 2017-06-15 17:19:09

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

@Alex78191 2017-06-19 00:17:15

When i can use it in Chrome?

@Dan Herbert 2017-07-10 19:17:33

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

@Alex L 2017-10-02 16:47:54

@jhpratt 2017-12-13 22:29:25

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.

@TylerH 2018-05-08 19:42:09

@jhpratt The world would be a very different place if browser vendors adhered strictly to the W3C's CSS specs.

@jhpratt 2018-05-08 21:35:03

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

@TylerH 2018-05-09 13:51:06

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

@sol 2017-09-25 13:55:34

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>

@cancerbero 2018-06-29 15:13:57

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!

@Eduard Florinescu 2018-02-01 14:18:25

At least up to and including CSS3 you cannot select like that. But it can be done pretty easily nowadays in JS, 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>

@Yukulélé 2018-01-20 20:22:01

yes: :has()

browser support: none

@Alireza 2017-06-16 18:06:57

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;

@innovati 2016-04-07 17:52:31

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.

@Suraj Naik 2014-03-21 12:58:43

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.

@nicodemus13 2014-05-15 09:04:41

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

@cobaasta 2011-06-30 14:00:09

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.

@Alireza 2017-06-16 18:08:12

This is just sibling selector, it's not child, parent... not really answering the question mate

@jeroen 2009-06-18 20:08:22

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.

@user914183 2011-08-26 13:46:58

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

@jeroen 2011-08-26 14:34:51

@Dominic Aquilina Take a look at the question, the OP is using a class, not a pseudo selector.

@Rounin 2017-02-18 17:06:00

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)

@Rounin 2017-07-12 16:40:34

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

@Salman A 2014-01-21 08:43:47

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.

@vsync 2014-02-19 21:33:39

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.

@Salman A 2014-02-20 04:09:48

actually, the selector would make a very fast browser look slow.

@Marc.2377 2018-06-09 00:15:36

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.

@Gaurav Aggarwal 2015-11-27 21:16:35

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.

@jcuenod 2015-11-30 20:15:40

The problem is that a CMS is generating the markup

@Sukhminder Parmar 2016-09-15 04:06:49

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

@Raseko 2011-11-23 09:03:14

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

@Ilya B. 2015-10-27 17:55:16

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

@Nathan Tuggy 2015-10-28 07:57:38

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?

@Ilya B. 2015-10-28 08:08:58

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. 2015-10-28 12:59:48

Added explanation (css section of jsfiddle, starting from "MAIN PART")... And I was mistaken - there may be any number of sublevels.

@Prabhakar 2015-10-14 10:08:04

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

@Marconi 2015-05-05 18:24:05

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

@Qwertiy 2015-11-20 12:06:29

Sadly, but now this feature is out of specification as I know...

@Idered 2011-08-13 10:13:50

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.

@Dan 2011-09-22 19:30:37

suppose using jquery patent() would be faster. This need testing, however

@yunzen 2013-04-16 15:33:22

@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

@Idered 2013-04-17 13:41:20

@HerrSerker I think #a! is an invalid selector, what should it select?

@yunzen 2013-04-17 15:31:45

@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

@BoltClock 2013-05-02 15:35:48

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.

@Redtopia 2014-03-29 05:19:28

@ldered, I cannot get your example to work. jsfiddle.net/5z5MV

@Idered 2014-03-29 22:16:16

@Redtopia It's because you haven't attached the polyfill

@Michael 2014-09-26 05:06:21

Can we get a polyfill that doesn't depend on jquery?

@opticyclic 2015-10-18 09:34:28

@Daniel Springer 2016-07-07 05:06:23

Isn't the OP asking for a CSS solution?

@toddmo 2017-05-01 19:54:08

How would you then stick an :after on that parent?

@TylerH 2018-06-06 13:42:34

Please add the contents of the script here, otherwise this is useless when GitHub is down.

@David Clarke 2013-05-16 22:04:58

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

@Robin van Baalen 2013-07-18 17:40:39

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.

@David Clarke 2015-12-19 19:27:31

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.

@Robin van Baalen 2015-12-19 19:36:50

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.

@David Clarke 2015-12-20 18:35:37

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.

@zcrar70 2009-12-14 14:51:14

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

@Rob W 2012-02-23 17:53:13

The < selector does not exist (verified using jQuery 1.7.1).

@Alastair 2013-05-02 05:10:13

Perhaps that <-syntax worked in 2009 but I've updated it (for 2013).

@Rory O'Kane 2013-05-08 22:12:06

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 2013-05-08 22:20:12

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.

@riverstorm 2012-02-13 11:22:34

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.

@Ivaylo Slavov 2012-07-24 18:22:49

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.

@riverstorm 2012-12-12 22:34:43

Totaly right Ivaylo! "a" is a non-block element, so can't use block elements inside it.

@Matthew James Taylor 2014-04-06 07:47:10

In HTML5 it is perfectly fine to put block elements inside links.

@Vangel Tzo 2014-04-10 14:39:06

@MatthewJamesTaylor and semantically it is perfectly wrong

@BoltClock 2015-12-28 15:54:58

... if it was semantically wrong, they wouldn't have allowed it in HTML5 where it wasn't before.

@Josh 2009-06-18 20:06:44

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;
}

@Josh 2009-06-18 21:53:32

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.

@Ricardo 2016-03-18 23:17:12

this is actually an simple and elegant solution and, in many cases, it makes sense to set the class on the parent.

@rgb 2011-08-16 04:43:30

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

@NullVoxPopuli 2011-11-10 16:56:42

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

@Paul Sweatte 2012-08-18 16:14:42

CSS selectors are a queue so selector order is evaluated rather than the document XPath or DOM hierarchy.

@yunzen 2013-04-16 15:35:31

@rgb At least that's what they told us.

@Mark Hurd 2009-06-18 20:09:01

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.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] How do I vertically center text with CSS?

19 Answered Questions

[SOLVED] Is it possible to apply CSS to half of a character?

16 Answered Questions

[SOLVED] When to use margin vs padding in CSS

  • 2010-02-03 03:20:12
  • Alex Angas
  • 686154 View
  • 2123 Score
  • 16 Answer
  • Tags:   css padding margin

13 Answered Questions

[SOLVED] Is there a "previous sibling" CSS selector?

  • 2009-11-30 04:06:36
  • Jourkey
  • 538722 View
  • 1158 Score
  • 13 Answer
  • Tags:   css css-selectors

18 Answered Questions

[SOLVED] CSS selector for first element with class

  • 2010-04-26 22:51:13
  • Rajat
  • 823096 View
  • 795 Score
  • 18 Answer
  • Tags:   css css-selectors

10 Answered Questions

[SOLVED] Complex CSS selector for parent of active child

  • 2008-09-05 00:01:36
  • Deeksy
  • 262844 View
  • 294 Score
  • 10 Answer
  • Tags:   css css-selectors

33 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

8 Answered Questions

[SOLVED] Which characters are valid in CSS class names/selectors?

  • 2009-01-15 23:37:39
  • Darryl Hein
  • 349664 View
  • 1124 Score
  • 8 Answer
  • Tags:   css css-selectors

11 Answered Questions

[SOLVED] What does the "+" (plus sign) CSS selector mean?

  • 2009-07-16 19:26:50
  • gday
  • 286085 View
  • 675 Score
  • 11 Answer
  • Tags:   css css-selectors

26 Answered Questions

[SOLVED] Set cellpadding and cellspacing in CSS?

Sponsored Content