Sunday, December 19, 2010

How to align a checkbox with its label?



Creating a simple checkbox is a piece of cake. Just put an input with type="checkbox" in your HTML and it is done. The issue of vertical alignment arises when you have to use a separate label element in front of this checkbox.


 The situation is like this. You have a checkbox and a label with small font size just next to it as shown in the code below:



<input type="checkbox" />
<label style="font-size: 10px;">This is the label</label&gt;


This will be displayed as:



Notice that the text is not vertically in the middle of  the checkbox, instead it is dropped down a bit.  To make it vertically aligned to the middle of the checkbox we can add following style to the label



position: relative; top:-2px;


Now the code becomes:




<input type="checkbox" />
<label style="font-size: 10px;position: relative;top: -2px;">This is the label</label>



and it will be displayed as:



Now see that the text is vertically aligned to the checkbox.

Adjust the value of top according to the font size and you are good to go. 



Short and simple.