CSS Blog and Knowledge Base

Aug
5

CSS Checkbox: Behind the Code and How it Works

Tags:
  • CSS Checkbox
  • How It Works
  • Checkbox CSS
  • It's 2014 and CSS still does not have a "quick and easy" way to style some form controls. Nowadays though, with a little creative CSS and a ultra convenient tool like CSS Checkbox, styling your checkboxes can be much easier than previously thought! Even though CSS Checkbox is easy and free, some people might want to know how CSS Checkbox actually works. CSS Checkbox kits are based off of what some people call the "Checkbox Trick" or "Checkbox Hack". This article assumes a basic understanding of HTML and CSS and will go on to explain in theory how the code works. When approaching styling CSS from a normal standpoint, one would want to style the DIV or other HTML element that needs to be styled. So when you want to style an INPUT with type "checkbox" or "radio", you would style the HTML INPUT element, correct? That's where things get tricky. HTML Checkbox and Radio Button are special in the sense that although they can be HTML block or inline elements, they cannot be styled in the same way as other comparable HTML elements. This mean that handy CSS properties like Border and Background will not apply at all to Checkbox and Radio HTML elements.

    The way around this seemingly insurmountable impasse is to link an HTML LABEL element to your HTML Checkbox and/or Radio Button elements using the LABEL element's "for" attribute, and then to apply your styling preferences to the LABEL element instead of the Checkbox or Radio Button element. Linking the LABEL element in this fashion ensures that the usability and interactivity still works properly even though you are not interacting with the Checkbox or Radio Button element itself. You'll notice below that the LABEL's "for" attribute must match the INPUT element's "id" attribute to properly link the two elements. The proper way to set up your INPUT and LABEL relationship can be seen as follows: After you've set up your HTML as shown above, the next thing you'll want to do is literally not display the actual INPUT element via your CSS like this: Then you can style the associated Label element by giving it a background image. The following example uses a background sprite image and background position of "0 0" to display the unchecked version of the checkbox background image. We use the "+" operator to link the INPUT and LABEL elements via CSS as well. In order to get the "Checked / Unchecked" effect and interactivity when clicking the LABEL element, we can apply a CSS Background Position shift to our LABEL on click with the CSS pseudo class ":checked" which can be seen as follows: As you can see, this is just one of the many great uses of CSS's relatively new Pseudo Class features. This explanation can hopefully provide a means to full understand and extend the tools that CSS Checkbox provides.

    Browse More Blog Articles