Pure CSS Toggle Centered Element Width


CSS only toggle the width of centered HTML DOM element. No JavaScript required. See demo first. Please click the following text to toggle the width of centered div:



centered div element

This demo uses the technique of CSS toggling in [3]. There are three main HTML elements in the demo:

<label for="element-toggle">click me to toggle width</label>
<input id="element-toggle" type="checkbox" />

<div id="toggled-element">centered div element</div>
  1. A visible HTML label element
  2. A invisible HTML input checkbox element, referenced by the above label element via for attribute.
  3. The element to be width-toggled. It is a div element in the demo.

When users click on the visible label element, the invisible input checkbox element becomes checked/unchecked by the click. Then the following CSS rules are used to toggle the width of the element according to whether the checkbox is checked or not.

label[for=element-toggle] {
  cursor: pointer;
  color: red;
}
#element-toggle {
  display: none;
}
#toggled-element {
  margin: auto;
  width: 100%;
  background-color: aqua;
  padding: 1rem;
}
#element-toggle:not(:checked) ~ #toggled-element {
  width: 60%;
}

There are three rules in above CSS code. The last rule is the most important part in this trick. It says if the element with id=element-toggle (i.e., the input checkbox) is not checked, the width of adjacent element with id=toggled-element (div element in this case) becomes 60%. If the input checkbox is checked, this rule is not applied to the div element, which makes the div element width: 100%;. The last CSS rule toggles the width of div according to whether the checkbox is checked or not.

To center a block element horizontally, use margin: auto; [2].


Tested on:

  • Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]
[2]CSS Layout - Horizontal & Vertical Align
[3]Pure CSS Toggle (Show/Hide) HTML Element