More on checkbox alignment
May 07, 2010 04:13:14 Last update: May 07, 2010 04:35:03
It seems that the key to aligning a checkbox with its label lies in the
line-height property of the label.
- This simple HTML snippet aligns well:
<!DOCTYPE HTML> <html> <head> <style type="text/css"> body { margin: 10px; font-family: sans-serif; } input.checkbox { clear: left; float: left; } label.checkbox { display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; } </style> </head> <body> <form id="dataform"> <input id="checkbox1" name="cb1" value="y" type="checkbox" class="checkbox"> <label for="checkbox1" class="checkbox">Checkbox 1</label> <input id="checkbox2" name="cb2" value="y" type="checkbox" class="checkbox"> <label for="checkbox2" class="checkbox">Checkbox 2</label> <input id="checkbox3" name="cb3" value="y" type="checkbox" class="checkbox"> <label for="checkbox3" class="checkbox">Checkbox 3</label> </form> </body> </html>
which is rendered like this:
- Change the font size of the label to
12pxthrows off the alignment:label.checkbox { font-size: 12px; display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; }
- In case 1, the height of the checkbox is
13pxwith3pxtop and bottom margin, for a total of19px, which is exactly the height of the label div. As can be seen from Firebug:
Checkbox layout Label layout 

In case 2, the height of the label div shrinks to15px, while the height of the checkbox remains the same:
Checkbox layout Label layout 

And that's the reason the label is shifted up relative to the checkbox.
- Change the line height in case 2 to
19pxfixes the problem:label.checkbox { font-size: 12px; line-height: 19px; display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; }
And you are free to change the font size as long as you keep the line height:label.checkbox { font-size: 24px; line-height: 19px; display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; }
- An alternative way is to change the top margin of the checkbox to match up the height of the label:
input.checkbox { margin-top: 8px; clear: left; float: left; } label.checkbox { font-size: 24px; line-height: 29px; display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; }
- You still need to tweak the height attribute of the checkbox in order for it to align in both IE and FF:
input.checkbox { height: 24px; clear: left; float: left; } label.checkbox { font-size: 24px; line-height: 29px; display: block; float: none; clear: none; margin-left: 20px; padding-bottom: 12px; }