DEV Community

Wes
Wes

Posted on β€’ Originally published at goulet.dev on

Conditional Styles with CSS :has

I was setting up a simple landing page for Fandwagon and just wanted some text to be strike-through when the user checks a checkbox. So far my landing page has no need for any JavaScript, and thankfully I can keep it that way and still get conditional styles with the :has() pseudo-class.

Demo

Code

First, the HTML - a simple form with a checkbox.

<form>
  <p>
    Want to know when it's ready?
    <span
      >I'll send you one email when it's ready, then delete your email address
      forever.</span
    >
  </p>
  <div>
    <input type="checkbox" switch name="subscribe" id="subscribe" />
    <label for="subscribe">Check this box to subscribe to updates</label>
  </div>
</form>
Enter fullscreen mode Exit fullscreen mode

And the CSS for the conditional strike-through

#example-form:has(input:checked) span {
  text-decoration: line-through;
}
Enter fullscreen mode Exit fullscreen mode

Breaking down the selector

The first part #example-form:has(input:checked) is basically saying "find the element with id of example-form that has a child input element that is checked".

:has is basically a very-flexible "parent selector".

Once we've selected the parent that contains the checked input then we select the descendent span element and apply the text-decoration: line-through style.

πŸ’₯ Done! No JavaScript needed!

You can get pretty far in conditional styling by combining :has and :checked pseudo-classes. If you have any cool example of combining the two then send me an email, I'd love to see!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay