CSS :has

By  on  

For as long as developers have written CSS code, we've been desperate to have a method to allow styling a parent element based child characteristics. That's not been possible until now. CSS has introduced the :has pseudo-class which allows styling a parent based on a relative CSS selector!

Let's have a look at a few use cases for :has in CSS:

/*
  If an `a` element contains an image, set the `a`'s display
*/
a:has(img) {
  display: block;
}

/*
  If a `figure` has a `caption` with a `multiline` class
  allow the `figure` to have any height
*/
figure {
  height: 200px;
}
figure:has(caption.multiline) {
  height: auto;
}

/*
  Hide an advert containing `div` until ads load
  and have been injected
*/
.ad-container {
  display: none;
}
.ad-container:has(.ad) {
  display: block;
}

/*
  If we have an `article` element without a heading,
  add top padding because `H1`s have top padding
*/
article:not(:has(h1)) {
  padding-top: 20px;
}

Apple's Safari is the first browser to support :has , though we should see others quickly follow suit as it's part of the official CSS spec. Now that we have this new pseudo-class, do you think you'll use it much? Or will you stick to your current workarounds?

Recent Features

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

Incredible Demos

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

  • By
    Image Data URIs with PHP

    If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves...

Discussion

  1. saithis

    Very useful new CSS feature, but please be careful with the advert example. It sucks if you are reading something and suddenly the text jumps around because some stupid ad finished loading and moves everything around.

  2. Thank you for this very insightful article.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!