Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style checkboxes as Toggle Buttons

On my website, users can post articles and tag them accordingly using some pre-set tags. These tags are in the form of checkboxes. Example below:

<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Aliens" /> Aliens
<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Ghosts" /> Ghosts
<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Monsters" /> Monsters

As you might know, the checkboxes will look something like this:

[ ] Aliens

[o] Ghosts

[ ] Monsters

I would like to do is have the checkbox being one large button with the value inside of it. And then make it have a "toggle" effect.

[ Aliens ] [ Ghosts ] [ Monsters ]

How would I go about doing this?

like image 549
Swen Avatar asked Mar 15 '13 15:03

Swen


People also ask

How do you style a toggle button?

You can use the :before and :after pseudo CSS selectors to modify the look and feel of the toggle button. Since :before is already used to create the circular toggle, I have used :after to add the text. Obviously, there are more ways to do this, and the below is a just a quick way to show you how to achieve this.

Can you style checkboxes?

A checkbox is an HTML element that takes input from the user. It is possible to style a checkbox using Pseudo Elements like :before, :after, hover and :checked. To style the checkbox the user first needs to hide the default checkbox which can be done by setting the value of the visibility property to hidden.

Can a checkbox be a button?

The checkbox button is useful for increasing clarity. Since the button only adds or removes entities, the user knows the action they will prompt upon click. The checkbox button also provides a clear visual affordance and a large target to take this action.


1 Answers

Check this out

HTML

<input id="chk_aliens" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Aliens" />
<label for="chk_aliens">Aliens</label>

<input id="chk_ghosts" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Ghosts" />
<label for="chk_ghosts">Ghosts</label>

<input id="chk_monsters" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Monsters" />
<label for="chk_monsters">Monsters</label>

CSS

.vis-hidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

label {
  margin: 10px;
  padding: 5px;
  border: 1px solid gray;
}

input:focus + label {
  border-color: blue;
}

input:checked + label {
  border-color: red;
}

input:focus:checked + label {
  border-color: green;
}

Note that the last selector may not work in older IE.

like image 179
Simon Avatar answered Sep 20 '22 00:09

Simon