Toggle Element (Dropdown/Menu) Visibility with CSS


Toggling element without the hassle of JavaScript is a good design choice for the application of dropdown/menu on a fast, responsive, mobile-friendly website. After consulting Google, the posts [1] and [2] are good tutorials for me. The following is my result.

Please first check:

Demo

Source Code for Demo (html):

toogle-element-visibility-with-css.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Toggle Element Visibilty with CSS</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  </style>
</head>
<body>

<div class="container">
  <div class="toggleable-window">
    <input class="toggle" type="checkbox" id="punch" checked>
    <label for="punch">&equiv;</label>
    <div class="content">content<br>content<br>content</div>
  </div>
</div>

</body>
</html>

Source Code for Demo (css):

style.css | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* pure css toggle-able window */
.toggleable-window input.toggle {
  display: none;
}

.toggleable-window label {
  font-size: 3em;
  font-weight:bold;
}

.toggleable-window label:hover,
.toggleable-window label:focus {
  cursor: pointer;
}

.toggleable-window input.toggle:checked ~ label {
  font-weight:normal;
}

.toggleable-window input.toggle:checked ~ div {
  display: none;
}


.toggleable-window div {
  position: absolute;
  width: 100%;
  background: yellow;
}

.container {
  position: relative;
  width: 10em;
}

If you prefer to use SASS for your CSS writing, here is the SCSS equivalent of above CSS:

style.scss | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* pure css toggle-able window */
.toggleable-window {
  input.toggle {display: none;}
  label {
    font-size: 3em;
    font-weight:bold;
    &:hover, &:focus {
      cursor: pointer;
    }
  }
  input.toggle:checked ~ label {font-weight:normal;}
  input.toggle:checked ~ div {display: none;}
  div {
    position: absolute;
    width: 100%;
    background: yellow;
  }
}

.container {
  position: relative;
  width: 10em;
}

References:

[1]Is it possible to toggle div visibility with CSS?
[2]HTML5 Window Toggle Events In Pure CSS3
[3][AngularJS] Toggle Element without JavaScript
[4][AngularJS] Dropdown Menu Using Directive