How to create a pure CSS toggle button…?

My general experience with programming is that you learn new skills and techniques on the job, which can be often painful as one can easily spend hours figuring out stuff or browsing tutorials…

For an application that I am developing, I wanted a simple, pure CSS toggle switch with the following parameters:

  • 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

It turned out that there aren’t so many great tutorials out there so here is what I came up with (codepen link):

HTML

CSS

First, let’s hide the original checkbox:

Format the label:

Part of the magic happens here. We are creating a two-column grid for the labels and we fit the width to the content. As we defined the same fraction size for the two columns, we will get equal width on both sides regardless of content. Just to note that for the position if you use absolute, you don’t need to set width: fit-content; — it really depends on how you want to use it.

To create the toggle:

Here instead of fixing the width and height, we are using percentages to always have the button stretched to half of the width of the whole container.

To format the text containers and bring them forward:

To move the button:

And finally to add some text colour changes:

Please shout out if you plan to use it in your project (I am just interested)!