Code and Stuff

Apr 8, 2012

CSS3 Toggle Fields

How it works

The toggle effect uses a hidden checkbox. CSS3 introduces the :checked pseudo class. This combined with the Adjacent sibling combinators will allow us to behave differently when the check box is selected and when not. To make check box change state upon a click on some text we will use a label for the checkbox. In HTML this translates to:
<input type="checkbox" class="check" id="check1"/>
<label for="check1" class="expand">
   Click here: no javascript involved
   <div class="details">
      Just HTML and CSS3 being awesome!
   </div>
<label>
While in this example the part that will expand is the label itself, this is not at all a requirement.

The CSS part includes also some transition effect. For the sake of simplicity the code below shows only important parts (no borders, shadows and colors):

.expand {
        height: 28px;
        font-size: 24px;
        overflow: hidden;
        display: block;

        transition-property: height;  
        transition-duration: 0.5s;
}

input.check:checked + .expand {
        height: 200px;
        transition-property: height;  
        transition-duration: 0.5s;
        display:block;
}

input.check {
        position: absolute;
        left: -10000px;
}
NOTE: all code is non vendor specific CSS3. You will have to add -moz- and similar to get to work on the different browsers.

Quite powerful

This method turns out to be quite powerful. The label does not have to be next to the checkbox so we can place it where ever we want () and the element next to the hidden checkbox will still get expanded. We can even have multiple label pointing to the same checkbox ().
Clicking here wont do much

on the label in the text it does

Even more

There are many more things involved and many more applications of this method. The major advantage is that it will not require javascript to be enabled. Here a post about an alert dialog without javascript.

A search in google will give you also many other uses of this "hack".

Accessibility

If not implemented correctly, this method is not very accesibility friendly. Multiple labels for a check box might confuse a screen reader and labels are not focussable. One quick fix for the latter could be:
input.check:focus ~ label {
        outline: dashed 1px silver;
}
But this will only work if the label follows the checkbox.

No comments: