Pure CSS Bootstrap Collapse
CSS only toggle Bootstrap collapse. No JavaScript required. Click the following button to see demo.
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
The above demo apply the technique of Bootstrap modal [2] to basic Bootstrap collapse.
The following is the source code for above demo.
HTML:
<!-- you can put the following line in your html head -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<div style="margin: 2rem;">
<label class="btn btn-primary" type="button" for="element-toggle">
Collapse Trigger
</label>
<input id="element-toggle" type="checkbox" />
<div class="collapse" id="collapseExample">
<div class="card card-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
</div>
</div>
The collapse trigger consists of visible label and invisible input checkbox elements. We apply .btn.btn-primary class to the label element to make it look like a button. If users click on the label element, the visibility of the collapse is toggled.
Note that in our pure CSS toggle, CSS animation effect during (collapsing) transitions is not implemented.
CSS:
#element-toggle {
display: none;
}
#element-toggle:checked ~ #collapseExample {
display: block;
}
Only two rules in CSS code:
- First rule make input checkbox element invisible.
- Second rule toggles the visibility of the collapse when users click on the label elements.
Tested on:
- Chromium 69.0.3497.81 on Ubuntu 18.04 (64-bit)
- Bootstrap 4.1.3
References:
[1] | Pure CSS Toggle (Show/Hide) HTML Element |
[2] | Pure CSS Bootstrap Modal |