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!
Structure
We’ll start with some basic HTML. The important things to note here are:
- Both the “view” and “edit” groups’ fields are contained within two container elements.
- Preceding both of those container elements is a lowly checkbox field (more on this later).
- Each view also contains a
label
tag, which will toggle the state of that field.
<input id="toggle" type="checkbox"> |
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; } |
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!