Quick tip: conditional form fields with CSS

As part of a tool I just wrote, I had the issue that one form field was dependent on another and I didn’t want to go the full way and create the field on demand with JavaScript but keep it to CSS. You can see the result here:

showing and hiding extra form fields when a checkbox is activated

A simple way to achieve this visually is to use the :checked pseudo and + selectors as you can see in this Fiddle:

The HTML is still the following:

<form>
    <input type="checkbox" id="moo">
    <label for="moo">Condition</label>
    <label>
        value for condition: 
        <input type="text" value="20">
     </label>
</form>

And the updated CSS:

label + label {
    padding-left: 1em;
    opacity: 0.1;
    visibility: hidden;
    transition: 0.5s;
}
:checked + label ~ label {
    opacity: 1;
    visibility: visible;
}

UPDATE: Safari fix.

As Safari doesn’t support multiple + selectors, replacing the second one with a ~ works. Get with it, Safari!