Showing and hiding conditional HTML without Javascript

May 21, 2013 Stephan Hagemann

Have you ever filled out an address form that had a checkbox for “my shipping address differs from my mailing address”? When you click that box a conditional form part gets revealed that allows you to enter another address. We had to build something very similar the other day and stumbled on a neat way to make the conditional part show and hide with CSS only.

Here is how:

<style>
  .conditional_form_part {
    display: none;
  }

  .conditional_form_part_activator:checked + .conditional_form_part {
    display: block;
  }
</style>

<form>
    Mailing address differs from home address
    <input class="conditional_form_part_activator" type="checkbox">

    <div class="conditional_form_part">
        some other content
    </div>
</form>

Here is a jsfiddle of the result:

As you can see from the CSS section, the trick is the combination of the :checked pseudo selector with the + selector. When elements like radio and checkbox are checked, the :checked selector applies. The + selector applies when an element immediately follows another element. In combination we can target the immediate sibling of a checked checkbox and use that for styling.

There are a couple of other CSS selectors that allow you to extend this example, e.g., the tilde operator, which selects any following element. Better brush up on your CSS selectors.

YMWBL – Your Mileage Will Be Limited

Note, that you would not be able to make this example work, if the checkbox were wrapped in a label (or any other element). There is no selector with which you could target the conditional form part in that case.

As far as structural queries go, CSS is limited in expressive power to only allow selection deeper into the document tree (i.e., with the > (child) selector) or downward within the current level (with + or ~), but never upwards within the tree.

About the Author

Biography

More Content by Stephan Hagemann
Previous
Two Simple Ways to Improve Content Delivery: Spatial and Temporal Locality
Two Simple Ways to Improve Content Delivery: Spatial and Temporal Locality

Have you ever seen an episode of Good Morning America or Breakfast Television aired in the afternoon or eve...

Next
Finding Pivotal
Finding Pivotal

The year is 2005. I’m one year out of school, and a year into a job doing PHP web development at a small de...

Enter curious. Exit smarter.

Learn More