There have been occasions where I’ve wished I was able to select a parent element with CSS–and I’m not alone on this matter. However, there isn’t such thing as a Parent Selector in CSS, so it simply isn’t possible for the time being.
In this tutorial we will walk through a few cases where having a CSS parent selector might come in handy, along with some possible workarounds. Let’s get started!
Wait, What’s a Parent Selector?
CSS selectors allow us to target elements, moving down and across the DOM tree, getting more specific as we do so. Here’s an example of the kind of selector you might find in Bootstrap–it travels down the DOM tree from the nav.navbar-dark
element, to the ul
, the li
, then finally the a.nav-link
.
.navbar-dark .navbar-nav .nav-item .nav-link { }
A parent selector would allow us to travel back up the DOM, targeting the parent elements of certain things. For example, we would be able to target the parent of .nav-link
elements by using:
.nav-link::parent { }
Note: this example is pure pseudo code, it does not exist nor suggest the best possible syntax!
Case 1: Styling Legacy Content
Styling legacy content, with dated markup and structure, is a classic challenge when redesigning a website. Before HTML5, for example, an image might typically have been wrapped with a p
, div
, or sometimes with a span
along with a nested p
used to wrap the image caption. There was no standard way to wrap an image and caption. Later, we adopted the figure
and figcaption
elements, making our document structure more semantic.
We want the images from the legacy content to appear as above. But since there may be more div
tags in our document, ones which don’t contain images at all, the following style declarations would be completely impractical.
.page-content div { padding: 15px; background-color: #f3f3f3; margin: 10px 0 20px; } .page-content div img { marging: 0 0 10px; } .page-content div .img-caption { color: #999; font-size: 12px; text-align: center; Wisplay: block; }
It would apply the background color, padding and margins to all div elements in the content. We actually want to apply these styles exclusively to div
elements which wrap an image and an image caption.
Case 2: Maintaining Video Ratio
Another example looks at maintaining embedded video (like from Youtube or Vimeo) ratio, as well as making the video fluid. These days, largely thanks to the investigative work by Dave Rupert and pals, it’s widely accepted that the best approach is to apply padding-top
or padding-bottom
to the parent element.
In a real world, however, we may would not know which element contains the video. We may find some embedded video wrapped within a div
or a p
without an identifiable class name, making it tricky to select the proper element on which to apply the styles.
Therefore, declaring the styles as follows is again impractical since it will impact all the divs within the .page-content
including ones which don’t contain an embedded video.
.page-content { width: 560px; margin-right: auto; margin-left: auto; margin-top: 30px; } .page-content div { position: relative; padding-bottom: 56.25%; } .page-content div iframe { position: absolute; top: 0; width: 100%; height: 100%; }
How wonderful it would be to directly select the video’s parent element!
Case 3: Responding to Form Input
In this example we have a form with several inputs. When we focus on one of the inputs, it is given a more prominent border color, highlighting the user’s position within the form.
Sometimes you also may come across the situation where not only the border color, but the element wrapping the input is highlighted, making the input even more prominent:
The parent element might be a div
or a p
. So, how can we properly select the parent element based on certain states of its descendants?
Possible Workarounds
As we’ve covered, there is no such thing as a parent selector, so selecting a parent isn’t possible. We might be tempted to sidestep the problem, by completely reconsidering the design so that selecting the parent is avoided. But if that isn’t possible then here are some potential approaches.
Using CSS :has()
Selector
The :has
selector is officially referred to as the relational pseudo-class. It matches elements based on their descendants, which are defined between the parentheses.
In the following example, it applies a background-color
to any div
containing an image caption. This seemingly addresses case 1.
.page-content div:has( .img-caption ) { padding: 15px; background-color: #ccc; }
Or, if we want to be more specific, we can rewrite it to match any div
tag with the .img-caption
as the direct descendant.
.page-content div:has( > .img-caption ) { padding: 15px; background-color: #ccc; }
This selector is drafted for CSS Selector Level 4 though no browsers implement it yet. We will have to wait a little longer before this selector comes to light. Until then, take a look at the following video course entitled CSS of the Future to find out how the selector works:
Using the jQuery Parent Selector
No single CSS solution can fix our issues here, so let’s see what JavaScript can do for us instead. In this example we are going to use jQuery for its robust APIs, convenience, and browser compatibility. At the time of writing, jQuery provides three methods to select parent elements.
parent()
; this method selects the immediate parent of the targeted element. We can leverage this method to address all our use cases mentioned earlier in the tutorial.
For example, we may use parent()
to add a special class to the wrapping element of the images within the content.
$( ".img-caption" ) .parent() .addClass( "has-img-caption" );
The above code will select the immediate element wrapping the image, regardless of the element type, adding the has-img-caption
class to give us more control over the element selection and styles, as follows.
parents()
notice the plural form of this method. This method allows us to select the parent elements from the immediate, up to the root of the document, unless a selector is specified as the argument.
$( ".img-caption" ) .parents() .addClass( "has-img-caption" );
Given the above example, the parents()
method selects all the way from the div
tag which immediately wraps the image, the next div
, and lastly the html
, adding the has-img-caption
class to all elements.
Such overkill is redundant. The only element that will likely need to have the class added, in this case, is the immediate div
element. Hence we pass it in the method argument.
$( ".img-caption" ) .parents( "div" ) .addClass( "has-img-caption" );
Here, the parents()
method will travel through the ancestor tree of the image, selecting any div
found and giving it the has-image-caption
class.
If that’s still overbearing, you can narrow the selection down to a single element by specifying the index. In the following example, we apply the class only to the first div
.
var $parents = $( ".caption" ).parents( "div" ); $parents[0].addClass( "has-img-caption" ); // select the first div add add the class.
parentsUntil()
; this method selects the parent elements up to but not including the element specified in the parentheses.
$( ".caption" ) .parentsUntil( ".page-content" ) .addClass( "has-img-caption" );
Given the above code, it will apply the has-img-caption
class to all the parent elements except the element with .page-content
.
In some cases, where you have gazillion nested elements, using the parentsUntil()
method is preferable. It is comparably faster than the parents()
method as it avoids using the jQuery selector engine (Sizzle) to travel across the entire DOM tree up to the document root.
Wrapping Up
Are we likely to have a CSS Parent Selector at some point in the future?
Probably not. The kind of parent selector that we’ve discussed above has been proposed numerous times, but it has never passed the W3C draft stage for several reasons. Those reasons largely focus on browser performance, owing to the way browsers evaluate and render pages. The closest thing we’ll have in the future is the relational selector, :has()
.
However, since the :has()
is not yet applicable, JavaScript and jQuery are currently the most reliable approach. Bear in mind that DOM Traversal is a costly operation which may badly affect your site’s rendering performance. Avoid using parents()
or parentsUntil()
with other heavy operations like animate()
, fadeIn()
or fadeOut()
.
Better yet, examine the HTML structure whenever possible to see if selecting the parent element can be avoided completely!