Why Can't We Select Parent Elements with CSS?
Published Tuesday, July 24, 2007 in CSS
Yea, why is that? And are they working on letting us do it?
It's a breeze with JavaScript and it could be extremely useful in CSS I think.
Imagine being able to select all paragraphs that only contain images:
p > img:only-child:parent() {
/* Would style the paragraph */
}
Because the first bit of that selector says that the image should be a direct descendant and only child of a paragraph-element we can be sure that only paragraphs with nothing but images are selected.
Or styling links that contain nothing but images:
a > img:only-child:parent() {
/* Would style the anchor */
}
Styling nested lists would be so much sweeter and would remove the need for the "has-children"-class so commonly used:
li > ul:parent() {
/* Would style <li>s that has <ul>s in them */
}
This would be great for marking which navigation-item is selected without the use of an ID in each <li>, like this:
#home-page #navigation a[href="/"]:parent(),
#archives-page #navigation a[href="/archives/"]:parent() {
font-weight: bold;
}
That would make the li containing the link pointing to /archives/ bold if you're on the archives-page (body#archives-page) and same for the home-link on the #home-page.
I know it's already possible to style the links without IDs using attribute-selectors, but there's no way of styling its parent.
Obviously you should be able to use multple :parent()s in a row to walk further up the tree.
Now that I think of it, if they implement this kind of functionality they might as well implement all the available JS-functions like nextSibling, previousSibling, etc, etc.
What do you think?






Comments
4 comments so far, why don't you post one too?
Wednesday, January 23, 2008 | View all comments by Thierry
It's interesting...
I never really needed it, and it never crossed my mind, but now that you talk about it I can surely see the evidence.
Yes, it would be nice. But I'd personally would prefer an Xpath like syntax to target childs/parents/branches.
I do think it would allow a greater simplicity than chaining the parentNode() and next¦previousSibling()
Wednesday, January 23, 2008 | View all comments by Andreas
Yes perhaps xpath-support in CSS would be nice, although I haven't worked much with xpath so can't really say much.
Just selector::parent(selector) (the way jQuery implements it) would make my day.
Wednesday, October 15, 2008
http://www.prototypejs.org/api/element/up
" up(element, [cssRule][, index = 0]) -> HTMLElement | undefined Returns element
Wednesday, October 15, 2008 | View all comments by Andreas
@Irtrt - Like I said, "It's a breeze with JavaScript", but why can't we do it with CSS?
Also, you don't need a lib to select parent elements, .parentNode works just fine.