Toggling visibility via CSS

Toggling elements basically means hiding them or displaying them for specific purposes. This is mostly achieved by using JavaScript or jQuery. But there is another way to do it, and that’s through CSS.

Here’s some screenshots on it will look. You can change any styles later if you want:

Before clicking
After clicking on ‘Heading’

Here’s the explanation. As you know, whenever you label any form element using the <label> tag, clicking on the label is the same as clicking on the element. What I did here was, I created a hidden checkbox element and toggled it using the label. The text ‘Heading’ is the label here. Using CSS’s adjacent sibling selector and :checked pseudo-selectors, I toggled its display from none to block and vice versa.

Here’s the markup:

  <label for=toggle><h1>Heading</h1></label>
  <input type=checkbox id=toggle hidden />
  <p>This is a paragraph.<br /> This was initially hidden.</p>

The CSS code that controls the toggling behaviour:

p {
  display: none;
#toggle:checked + p {
  display: block;

The :checked pseudo-selector applies the style to those checkboxes which are in checked state and the ‘+’ i.e. adjacent sibling selects the <p> tag just after the checked checkbox. So whenever the checkbox is checked it appears and disappears when unchecked. Simple, no JavaScript needed.


2 thoughts on “Toggling visibility via CSS

Your Thoughts -

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s