Radio/checkbox alignment in HTML/CSS
Asked Answered
A

13

79

What is the cleanest way to align properly radio buttons / checkboxes with text? The only reliable solution which I have been using so far is table based:

<table>
<tr>
    <td><input type="radio" name="opt"></td>
    <td>Option 1</td>
</tr>
<tr>
    <td><input type="radio" name="opt"></td>
    <td>Option 2</td>
</tr>
</table>

This may be frown upon by some. I’ve just spent some time (again) investigating a tableless solution but failed. I’ve tried various combinations of floats, absolute/relative positioning and similar approaches. Not only that they mostly relied silently on an estimated height of the radio buttons / checkboxes, but they also behaved differently in different browsers. Ideally, I would like to find a solution which does not assume anything about sizes or special browser quirks. I’m fine with using tables, but I wonder where there is another solution.

Agnola answered 28/12, 2008 at 17:40 Comment(3)
I set up a JSFIddle to illustrate some of the suggestions: jsfiddle.net/casebash/XNJxT/906Shoelace
"align properly what o you mean? What counts as properly aligned?Sympathizer
you can align in percentage : for myself I use : vertical-align: -15%; on the input tagMahaliamahan
A
121

I think I have finally solved the problem. One commonly recommended solution is to use vertical-align: middle:

<input type="radio" style="vertical-align: middle"> Label

The problem, however, is that this still produces visible misalignments even though it should theoretically work. The CSS2 specification says that:

vertical-align: middle: Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

So it should be in the perfect centre (the x-height is the height of the character x). However, the problem seems to be caused by the fact browsers commonly add some random uneven margins to radio buttons and checkboxes. One can check, for instance in Firefox using Firebug, that the default checkbox margin in Firefox is 3px 3px 0px 5px. I'm not sure where it comes from, but the other browsers seem to have similar margins as well. So to get a perfect alignment, one needs to get rid of these margins:

<input type="radio" style="vertical-align: middle; margin: 0px;"> Label

It is still interesting to note that in the table based solution the margins are somehow eaten and everything aligns nicely.

Agnola answered 20/5, 2009 at 21:55 Comment(7)
Really nice answer - well researched, and it works. The more I look at CSS the more localised margin and padding settings seem to be the key. Thanks!Neolatin
as of 18.Apr.2010 this solution doesnt work in Firefox 3.6.3 for winDiplo
some nice css for this, so you don't have to style every button and box - input[type="radio"], input[type="checkbox"] {vertical-align: middle; margin: 0px; }Threesome
Would cssreset fix the different styles?Inge
FYI, the px after 0 is redundant. When the CSS value is 0, the unit doesn't matter, so margin:0 would suffice.Deutschland
I've found that "margin:0; padding:0;" works even a little bit better.Clemence
Remember to check the vertical-align of other elements in the same line (eg: <label>) when using this solution.Aetna
I
31

The following works in Firefox and Opera (sorry, I do not have access to other browsers at the moment):

<div class="form-field">
    <input id="option1" type="radio" name="opt"/>
    <label for="option1">Option 1</label>
</div>

The CSS:

.form-field * {
    vertical-align: middle;
}
Irresistible answered 28/12, 2008 at 17:40 Comment(3)
i dont understand why your answer wasn't accepted, it's the simplest working one for all major browsers (as of 18.Apr.2010)Diplo
Please note that the DOCTYPE of your document should be STRICT to see the effects of VERTICAL-ALIGN.Fortaleza
I think the reason this wasn't accepted as the answer is because, as the answer that was selected says, some browsers add asymmetric margin values, which stop this approach from working.Eskil
A
14

I found the best and easiest way to do it is this one because you don't need to add labels, divs or whatsoever.

input { vertical-align: middle; margin-top: -1px;}

Argumentum answered 28/10, 2010 at 15:2 Comment(2)
It's the margin-top:-1px; that's the extra sauce that gets my vote. I have a radio inside a span I'm using as a button. putting only the vertical-align for the radio style puts the radio just crossing the bottom of the span. putting the vertical-align in the span style leaves the button at the top. Only the margin-top seems to have no effect. But put them together and voilaArad
-1. This is a bad idea, you are causing the radio element shift up which cause it to not line up with the other surrounding elements. Go try it with several radio input one after another with other elements on the sides.Monas
K
7

I wouldn't use tables for this at all. CSS can easily do this.

I would do something like this:

   <p class="clearfix">
      <input id="option1" type="radio" name="opt" />
      <label for="option1">Option 1</label>
   </p>

p { margin: 0px 0px 10px 0px; }
input { float: left; width: 50px; }
label { margin: 0px 0px 0px 10px; float: left; }

Note: I have used the clearfix class from : http://www.positioniseverything.net/easyclearing.html

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */
Konstanze answered 28/12, 2008 at 18:7 Comment(3)
Thank you for the response, but I’m afraid it does not solve the alignment problem. I should have been clearer. My aim is to vertically align the checkboxes / radio buttons with their labels.Agnola
You can do this with my code. Play about with the margin on the label, and you can also add this to the input element if you want. So the label { margin: 10px 0px 0px 10px; float: left; } would push the label down 10 pixels.Konstanze
You can do that, but one of the points in the original question was not to assume anything about sizes of radio buttons / checkboxes. Most likely my question was too optimistic.Agnola
H
4

This is a bit of a hack but this CSS seems to get it working very nicely in all browsers the same as using tables (apart from chrome)

input[type=radio] { vertical-align: middle; margin: 0; *margin-top: -2px; }
label { vertical-align: middle; }
@media screen and (-webkit-min-device-pixel-ratio:0) {
 input[type=radio] { margin-top: -2px; }
}

Make sure you use labels with your radios for it to work. i.e.

<option> <label>My Radio</label>
Hedjaz answered 8/7, 2009 at 22:34 Comment(1)
The media thing helped me a lot with mobile devices. Thx!Warehouseman
U
3

If your label is long and goes on multiple rows setting the width and display:inline-block will help.

.form-field * {
  vertical-align: middle;
}
.form-field input {
  clear:left;
}
.form-field label { 
  width:200px;
  display:inline-block;
}

<div class="form-field">
    <input id="option1" type="radio" name="opt" value="1"/>
    <label for="option1">Option 1 is very long and is likely to go on two lines.</label>
    <input id="option2" type="radio" name="opt" value="2"/>
    <label for="option2">Option 2 might fit into one line.</label>
</div>
Unreflecting answered 9/1, 2011 at 13:7 Comment(0)
S
2

I found the best fix for this was to give the input a height that matches the label. At least this fixed my problem with inconsistencies in Firefox and IE.

input { height: 18px; margin: 0; float: left; }
label { height: 18px; float: left; }

<li>
  <input id="option1" type="radio" name="opt" />
  <label for="option1">Option 1</label>
</li>
Silverman answered 21/10, 2010 at 23:38 Comment(1)
Matching height fixed my radios. Not checkboxes but not worried as our site.css is fairly complex.Thionate
L
2

The following code should work :)

Regards,



<style type="text/css">
input[type=checkbox] {
    margin-bottom: 4px;
    vertical-align: middle;
}

label {
    vertical-align: middle;
}
</style>


<input id="checkBox1" type="checkbox" /><label for="checkBox1">Show assets</label><br />
<input id="checkBox2" type="checkbox" /><label for="checkBox2">Show detectors</label><br />
Lima answered 19/4, 2011 at 19:20 Comment(0)
L
1

This is a simple solution which solved the problem for me:

label 
{

/* for firefox */
vertical-align:middle; 

/*for internet explorer */
*bottom:3px;
*position:relative; 

padding-bottom:7px; 

}
Lucais answered 21/6, 2011 at 8:27 Comment(0)
Y
1

There are several ways to implement it:

  1. For ASP.NET Standard CheckBox:

    .tdInputCheckBox
    { 
    position:relative;
    top:-2px;
    }
    <table>
            <tr>
                <td class="tdInputCheckBox">                  
                    <asp:CheckBox ID="chkMale" runat="server" Text="Male" />
                    <asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
                </td>
            </tr>
    </table>
    
  2. For DevExpress CheckBox:

    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
    <dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
    
  3. For RadioButtonList:

    <asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
       <asp:ListItem>Yes</asp:ListItem>
       <asp:ListItem>No</asp:ListItem>
    </asp:RadioButtonList>
    
  4. For Required Field Validators:

    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
    
Yvette answered 29/11, 2011 at 21:25 Comment(0)
M
1

Below I will insert a checkbox dynamically. Style is included to align the checkbox and most important to make sure word wrap is straight. the most important thing here is display: table-cell; for the alignment

The visual basic code.

'the code to dynamically insert a checkbox

Dim tbl As Table = New Table()
Dim tc1 As TableCell = New TableCell()
tc1.CssClass = "tdCheckTablecell"

'get the data for this checkbox
Dim ds As DataSet
Dim Company As ina.VullenCheckbox
Company = New ina.VullenCheckbox
Company.IDVeldenperScherm = HETid
Company.IDLoginBedrijf = HttpContext.Current.Session("welkbedrijf")
ds = Company.GetsDataVullenCheckbox("K_GetS_VullenCheckboxMasterDDLOmschrijvingVC") 'ds6

'create the checkbox

Dim radio As CheckBoxList = New CheckBoxList
radio.DataSource = ds
radio.ID = HETid
radio.CssClass = "tdCheck"
radio.DataTextField = "OmschrijvingVC"
radio.DataValueField = "IDVullenCheckbox"
radio.Attributes.Add("onclick", "documentChanged();")
radio.DataBind()

'connect the checkbox

tc1.Controls.Add(radio)
tr.Cells.Add(tc1)
tbl.Rows.Add(tr)

'the style for the checkbox

input[type="checkbox"] {float: left;   width: 5%; height:20px; border: 1px solid black; }

.tdCheck label {     width: 90%;display: table-cell;    align:right;}

.tdCheck {width:100%;}

and the HTML output

<head id="HEAD1">
    <title>
        name
    </title>
    <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR" /><meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE" />
</head>
<style type='text/css'>
input[type="checkbox"] {float: left;   width: 20px; height:20px;  }
.tdCheck label {     width: 90%;display: table-cell;    align:right;}
.tdCheck {width:100%;}
.tdLabel {width:100px;}
.tdCheckTableCell {width:400px;}
TABLE
{

vertical-align:top;
border:1;border-style:solid;margin:0;padding:0;border-spacing:0;
border-color:red;
}
TD
{
vertical-align:top; /*labels ed en de items in het datagrid*/
border: 1;  border-style:solid;
border-color:green;
    font-size:30px  }
</style>
<body id="bodyInternet"  > 
    <form name="Form2" method="post" action="main.aspx?B" id="Form2">
        <table border="0">
            <tr>
                <td class="tdLabel">
                    <span id="ctl16_ID{A}" class="DynamicLabel">
                        TITLE
                    </span>
                </td>
                <td class="tdCheckTablecell">
                    <table id="ctl16_{A}" class="tdCheck" onclick="documentChanged();" border="0">
                        <tr>
                            <td>
                                <input id="ctl16_{A}_0" type="checkbox" name="ctl16${A}$0" />
                                <label for="ctl16_{A}_0">
                                    this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp  
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input id="ctl16_{A}_1" type="checkbox" name="ctl16${A}$1" />
                                <label for="ctl16_{A}_1">
                                    ITEM2
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input id="ctl16_{A}_2" type="checkbox" name="ctl16${A}$2" />
                                <label for="ctl16_{A}_2">
                                    ITEM3
                                </label>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
</form>
</body>

Mersey answered 6/1, 2013 at 7:21 Comment(0)
G
1

@sfjedi

I've created a class and assigned the css values to it.

.radioA{
   vertical-align: middle;
}

It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.

Gusset answered 22/8, 2013 at 10:42 Comment(0)
B
-1

input[type="radio"], input[type="checkbox"] {
    vertical-align: middle;
    margin-top: -1;
}
Bharat answered 22/6, 2017 at 10:31 Comment(1)
This doesn't work for me on Firefox 58 , is it some kind of nonstandard CSS?Superannuate

© 2022 - 2024 — McMap. All rights reserved.