Sitemap

Capturing click with CSS

1 min readApr 9, 2016

--

CSS does not currently provide a click pseudo-class like it does for :hover or :focus.

Restyling an element on click is a very common use case, however, and we would like to cleanly do so without resorting to javascript when it’s not needed.

Get Ning Xia’s stories in your inbox

Join Medium for free to get updates from this writer.

The simplest way to capture a click event with pure CSS is with a hidden checkbox for which we expose the label.

<input type=”checkbox” id=”click-control”/>
<label for=”click-control” />
<div class=”picture”/>

The above code takes advantage of how a click on the label registers as a click on its associated checkbox.

#click-control {
display: none;
}
#click-control:checked ~ .picture { /* change styles, animate, etc */}

The rest is taken care of by the :checked pseudo-class and some basic combinator selection.

See this in action in a very short and straightforward fiddle here: https://jsfiddle.net/1hdr73u8/4/

Stay tuned for more on CSS combinators and how much you can do with them.

--

--

Ning Xia
Ning Xia

Written by Ning Xia

Software Engineer. Node.js, React, Go, Java.