Sometimes you are not able to use JavaScript but you want to show and hide some div. The good situation for that is when you must create e.g. “toggle button” to show and hide some content on click (only with pure CSS) in old application where you do not have access to JavaScript code or you are not able to modify JS code. Than it is useful to know how to toggle visibility without JavaScript, just by pure HTML and CSS. It is possible, and very easy!
Table of Contents
Toggle visibility in pure CSS without JavaScript
So let’s say that you want to toggle visibility of some content totally without JavaScript usage, just in pure CSS. Than you must create 3 elements:
- input – checkbox with id, eg. “trigger”
- label – we treat it as toggle button
- box – simple div with content
Input checkbox must be placed just before the box. Label can be placed where ever you want.
<label for="trigger">Toggle box</label> <div> OTHER HTML CONTENT </div> <input id="trigger" type="checkbox"> <div class="box"> SHOW / HIDE BOX </div>
Then, to toggle visibility of some content on click in pure CSS you must use one CSS trick with “+” selector. Label with attribute “for” checks/unchecks input checkbox, and CSS below rule toggle visibility of the box with content. Hide input checkbox by display: none
rule.
.box { display: none; background: #ccc; width: 200px; height: 100px; } #trigger:checked + .box { display: block; }
As result you should have something like in images below:
Of course, at the end you should hide the input checkbox by display: none;
in CSS.
#trigger { display: none; }
Where to use toggling visibility in pure CSS without JavaScript?
Basing on this method you can create eg. dropdown menu without JavaScript. So simply on click of the menu header you can toggle the visibility of the submenu. This is a very practical example of toggling the visibility of content just in pure CSS, without JavaScript. But you can use in in many other situations, like in the forms – to show/hide some notifications when user check or uncheck checkbox, or in showing alerts one the website or web app.