Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

Showing and hiding conditional HTML without Javascript

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:

  .conditional_form_part {
    display: none;

  .conditional_form_part_activator:checked + .conditional_form_part {
    display: block;

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

    <div class="conditional_form_part">
        some other content

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.

  1. Trevor says:

    While it’s not perfect, adding a label with for attribute next to the input (with a proper ID) does give more context to the checkbox’s purpose. It’s also worth mentioning this technique won’t work below IE9 without a Javascript fallback. For modern sites and modern browsers, though, it’s a really simple way to show and hide content.

  2. Feno says:

    what if I want to apply class according to parameter value??
    can you help me with that??
    i want to use class something like .rtl{dir = “rtl” float = “right”}
    if ‘lang’ parameter = ‘AR’, that means Arabic language
    anf if not leave the default

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *