Fancy form elements with CSS3
Feb 29, 2012 | In CSS, Tutorials |Today, I’ll show how to style checkboxes and radio buttons in web forms with CSS3. Nowadays in web design, almost everything can be controlled with only CSS. This tutorial will allow you to further customize your web pages. However, this only works in webkit based browsers, so keep that in mind when you use this in your project.
Demo:
HTML
All you need is the HTML for checkboxes and radio buttons:
<input type="checkbox" id="checkthis"> <input type="radio" name="radiobutton" id="radio1"> <input type="radio" name="radiobutton" id="radio2">
Feel free to make your own wrapper HTML around this.
CSS
The CSS is slightly more complicated than the HTML.
First of all, we’ll need a very important line of CSS.
input[type=checkbox],input[type=radio] { -webkit-appearance:none; }
This basically “resets” the checkboxes and radio buttons, which means it discards all the styles the operating system and the browser place on them. You’re left with nothing at all, which is why we have to build from the ground up.
Now, we can continue with the basic styles for both checkboxes and radio buttons.
input[type=checkbox],input[type=radio] { -webkit-appearance:none; background:#fff; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; border:3px solid #d5d5d5; display:inline-block; width:18px; height:18px; -webkit-border-radius: 3px; vertical-align:text-top; padding: 0; }
Most of the styles are self-explanatory. No padding, a background, a border, a border-radius. However, the “vertical-align:text-top” helps out with positioning the check box or radio box. Try deleting this line and see what happens; the checkboxes or radio buttons move, and change the layout.
We also need to add a simple style rule to change the border color on hover. This makes the checkboxes/radio buttons more interactive.
input:hover { border:3px solid #c5c5c5; }
Next, we can style the “checkmark” inside the checkbox when it’s checked.
input[type=checkbox]:checked:after { content:"\00a0"; display:block; width:3px; height:6px; border:solid #a5a5a5; position:relative; left:4px; top:1px; -webkit-transform:rotate(45deg); -moz-transform:rotate(45deg); -o-transform:rotate(45deg); border-width:0 2px 2px 0; }
Here, “content:”