Fun with Stateful CSS: A View/Edit Screen

16 October 2013

I’ve previously blogged about using the concept of “stateful CSS” to indicate when your application is in the middle of a potentially long-running process. In that post, we looked at how to create a simple “view/edit” screen, but we relied on JavaScript to swap out CSS classes. Fortunately, there’s an easier way: using a checkbox!


We’ll start with some basic HTML. The important things to note here are:

<input id="toggle" type="checkbox">
<div class="view">
<p>Name: Test</p>
<label class="button" for="toggle">Edit</label>
<div class="edit">
<label for="name">Name:</label>
<input type="text" value="Test" />
<label class="button" for="toggle">Done</label>

This checkbox field is the key to the whole thing: it will store the state of whether we’re in “edit” mode or not (if it’s checked, we are). We’ll use the label tags in each section to toggle its value, and CSS to show and hide the “view” and “edit” fields based on whether it’s checked.

Behavior (in style!)

The CSS is strikingly minimal:

.edit, #toggle { display: none; }
#toggle:checked ~ .view { display: none; }
#toggle:checked ~ .edit { display: block; }

First, we hide the “edit” view and the checkbox by default. We then use the :checked and ~ (“general sibling”) selectors to hide the “view” panel and show the “edit” panel only when our checkbox-turned-state-machine is checked.

Update: After some feedback that the functionality of the example below was incomplete, editing the “name” property now persists after clicking “Done”.

See the Pen uAaCe by Tim G. Thomas (@TimGThomas) on CodePen

In the coming weeks, we’ll see some more UI patterns you can build without JavaScript, so stay tuned!