How often have you been styling something and thought to yourself, “If only CSS could apply a style to the parent element”?
CSS already has a descendant selector, >
, that allows us to select only the elements that belong to a certain element, but there is no equivalent <
selector to go the other way.
Adding a parent selector to CSS has been requested for a long time, and various different syntaxes have been proposed. We never set out to add a parent selector to CSS but as a side-effect of another feature we are building we had nearly all of the pieces in place.
Ladies and Gentlemen may I present: the $parent
selector.
It works with our element query plugin EQCSS, to learn more about how to get started with element queries check out elementqueries.com
When you write an element query you create a responsive context into which those styles apply. A simple element query might look like this:
@element '.widget' {
.widget {
background: red'
}
}
Now the styles inside can apply to any element, including other .widget
elements on the page, so we use style scoping to apply our styles to the element(s) which match our query with the $this
keyword. In the example below every .widget
that matches the condition will get the styles applied to $this
, but the styles applied to .widget
will apply to all .widget
elements on the page at any time a .widget
element meets the responsive condition.
@element '.widget' {
$this {
background: green;
}
.widget {
background: red;
}
}
This is style scoping. To target the parent of an element using the $parent
selector, first create a responsive context. Now anywhere you use the $parent
selector inside this query it will target the element containing $this
, the element that matches the query
@element '.widget {
$parent {
background: red;
}
}
Now the next time you encounter a situation where you wish you could target the parent of something, you can!
Examples
Applying different padding to a parent element based on the number of icons present inside
Changing
background-color
of parent when an input has enough characters
Support
The
$parent
selector works using EQCSS in every browser IE8 and up. Here's a screenshot, or test it yourself!