Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically aligning a checkbox

I have looked at the different questions regarding this issue, but couldn't find anything that works due to limitations in my markup.

My markup looks like so (unfortunately as this is generated by some backend, I am unable to change the markup).

<ul>             <li>         <input type="checkbox" value="1" name="test[]" id="myid1">         <label for="myid1">label1</label>     </li>     <li>         <input type="checkbox" value="2" name="test[]" id="myid2">         <label for="myid2">label1</label>     </li> </ul> 

I need the checkbox to be on the right and centered vertically in the <li>

Currently, this is styled as:

li input{    display: inline-block;    float: right;    margin-right: 10px; } 

I have tried using various values for vertical-align, but that doesn't seem to help. Also, in some cases the label can be very long and span multiple lines. The checkbox would still need to be able to vertically center itself when the height of the li is arbitrary.

How can I go about achieving this?

like image 755
F21 Avatar asked Mar 22 '12 01:03

F21


People also ask

How do I align checkboxes?

Method 1: By making the position of checkbox relative, set the vertical-align to the middle can align the checkboxes and their labels. Here, we have made the position of the checkbox relative to the label. So the checkboxes are aligned according to the label.

How do I align a checkbox horizontally?

Set the checkbox horizontally by including the data-type = "horizontal" to the fieldset. You can select the checkbox button more than one at a time.


2 Answers

Vertical alignment only works on inline elements. If you float it, then I don't think it is treated as part of that stream of inline elements any more.

Make the label an inline-block, and use vertical alignment on both the label and the input to align their middles. Then, assuming it is okay to have a specific width on the labels and checkboxes, use relative positioning instead of floating to swap them (jsFiddle demo):

input {     width: 20px;      position: relative;     left: 200px;      vertical-align: middle; }  label {       width: 200px;      position: relative;     left: -20px;      display: inline-block;     vertical-align: middle; } 
like image 153
Supr Avatar answered Oct 12 '22 06:10

Supr


Its not a perfect solution, but a good workaround.

You need to assign your elements to behave as table with display: table-cell

Solution: Demo

HTML:

<ul>             <li>         <div><input type="checkbox" value="1" name="test[]" id="myid1"></div>         <div><label for="myid1">label1</label></div>     </li>     <li>         <div><input type="checkbox" value="2" name="test[]" id="myid2"></div>         <div><label for="myid2">label2</label></div>     </li> </ul> 

CSS:

li div { display: table-cell; vertical-align: middle; } 
like image 37
Starx Avatar answered Oct 12 '22 07:10

Starx