How to create a pure CSS toggle button…?

  • have text on the button not next to it
  • be symmetrical on both sides regardless of text
  • be reusable in any setting, avoid having to set width based on text length

HTML

<input type=”checkbox” id=”toggle” class=”toggleCheckbox” />
<label for=”toggle” class=’toggleContainer’>
<div>Looooong</div>
<div>Short</div>
</label>

CSS

.toggleCheckbox {
display: none;
}
.toggleContainer {
position: relative;
display: grid;
grid-template-columns: repeat(2, 1fr);
width: fit-content;
border: 3px solid #343434;
border-radius: 20px;
background: #343434;
font-weight: bold;
color: #343434;
cursor: pointer;
}
.toggleContainer::before {
content: '';
position: absolute;
width: 50%;
height: 100%;
left: 0%;
border-radius:20px;
background: white;
transition: all 0.3s;
}
.toggleContainer div {
padding: 6px;
text-align: center;
z-index: 1;
}
.toggleCheckbox:checked + .toggleContainer::before {
left: 50%;
}
.toggleCheckbox:checked + .toggleContainer div:first-child{
color: white;
transition: color 0.3s;
}
.toggleCheckbox:checked + .toggleContainer div:last-child{
color: #343434;
transition: color 0.3s;
}
.toggleCheckbox + .toggleContainer div:first-child{
color: #343434;
transition: color 0.3s;
}
.toggleCheckbox + .toggleContainer div:last-child{
color: white;
transition: color 0.3s;
}

--

--

--

Communication, data, peace research and a bit of egyptology

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

TJBot Introduces Me to IoT & Watson Services

Chapter 5 Standing Guard When Python Breaks Free

Summary of Webinar on Industry use cases of Kubernetes

ADVANCE CSS GRID for WEB/APP FRONTEND

SAML Bearer Grant Type with WSO2 Identity Server 5.4.0

A WordPress Away…

Creating a Custom Setup wit h tmux Commands

images/scripting/devenv.png

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Balint Hudecz

Balint Hudecz

Communication, data, peace research and a bit of egyptology

More from Medium

Breadcrumbs… Not just for the birds!

How to create a Dynamic Digital Clock

Diving into CSS Animations

CSS: what is the difference between rem, em, px, & vw/vh units