HTML & CSS
Article
By Guy Routledge

AtoZ CSS Quick Tip: Styling with General Sibling Selector

By Guy Routledge

This article is a part of our AtoZ CSS Series. You can find other entries to the series here.
You can view the full transcript and screencast for General Sibling here.

Welcome to our AtoZ CSS series! In this series I’ll be exploring different CSS values (and properties) beginning with a letter from the alphabet. We know that sometimes screencasts are just not enough, in this article we’ve added a new quick tip about General Sibling for you.

cssAZ-G2.jpg-01

G is for General Sibling

In the video covering letter G, we looked at the General Sibling selector which allows styling of a sibling element. There’s also the other child and sibling selectors for traversing down/across an element tree.

But what about parent selectors? Well, despite the multiple use-cases of needing to select a parent element based on whether it contains certain children, this feature is not currently available in CSS.

But the good news is that they’ve made it into the CSS Selectors Level 4 spec. Woo Hoo! The parent selector, or the subject of the selector as it’s also called, allows you to select a parent element for styling. The latest draft of the spec uses an exclamation mark after the given selector to set the subject element.

The classic example of when you might want to style a parent element is in a menu. A navigation menu is normally an unordered list with a series of list items. Sometimes you may have a sub-menu that may be shown or hidden as a dropdown. It’s always been tricky to style the parent list item that has a sub menu without adding a class. With the new parent selector, it’s possible to achieve without one:

.main-menu li! .sub-menu {
  /* add styles to signify that this item has a submenu */
}

The Level 4 Selectors spec is still a work in progress, and I don’t know of any browser that supports it all yet. But when it does get released it will be a wonderful day!

More:
  • Parent selector looks very interesting,
    I find it useful to target a container element has an item selected/changed somehow
    maybe to create something like a split button, when you select an item from its drop down list the button icon will reflect the selected item

    Thanks

Recommended
Sponsors
Get the latest in Front-end, once a week, for free.