I’ve been using this technique for over a year, but I haven’t seen it in use anywhere else. In brief, I’m formalizing display “states” or “modes” using CSS classes. I’ve tried searching for “css modes”, “css states”, “stateful css”, etc. but if it exists then it doesn’t use any of those names.
Here’s a simple example of what I’m doing. The example is a responsive text input, the sort that would talk to the server and tell you dynamically whether the username you’ve chosen is already taken.
Markup:
<div id="username-container" class="username-mode-ready">
<!-- input -->
<label for="username" class="username-label">Username:</label>
<input type="text" id="username" class="username-input" />
<!-- icons -->
<img src="error.png" class="icon error"/>
<img src="ok.png" class="icon accepted"/>
<img src="loading.gif" class="icon loading"/>
<!-- messages -->
<p class="message error">
That username is not available.
</p>
<p class="message accepted">
That username is available!
</p>
<p class="message loading">
Loading ...
</p>
</div>
CSS:
/* Default = hidden */
#username-container .error,
#username-container .accepted,
#username-container .loading {
display : none;
}
/* Show when appropriate */
#username-container.username-mode-error .error,
#username-container.username-mode-accepted .accepted,
#username-container.username-mode-loading .loading {
display : block;
}
Now we would add our Javascript. When we go to the server we’ll do:
$('username-container').className = 'username-mode-loading';
And when we return, we’ll do one of the following based on the server response:
$('username-container').className = 'username-mode-accepted'; // Username available
$('username-container').className = 'username-mode-error'; // Username taken
This way, we can just change the className of the container to see different display modes without the need for manipulating element.style.display on a million different elements. We can also do more than show/hide:
CSS:
/* Set label color to green or red depending on availability */
#username-container.username-mode-accepted .username-label {
color : green;
}
#username-container.username-mode-error .username-label {
color : red;
}
Or apply styles across multiple modes:
Markup:
<img alt="Whew! I searched as hard as I could!" src="done-searching.png" class="icon done-searching"/>
CSS:
/* New icon should display in accepted and error modes */
#username-container .done-searching {
display : none;
}
#username-container.username-mode-accepted .done-searching,
#username-container.username-mode-error .done-searching {
display : block;
Has this technique already been described? I’m about to start calling it mode-oriented CSS, for want of a name when I explain it to people, but I’d rather use the nice, real, Googlable name if there is one.
Check out these articles that kind of cover some of these ideas:
Short answer: I don’t know 😉