[html] Radio/checkbox alignment in HTML/CSS

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.

This question is related to html css checkbox radio-button

The answer is


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 */

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;
}

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>

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;
}

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>

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>


_x000D_
_x000D_
input[type="radio"], input[type="checkbox"] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -1;_x000D_
}
_x000D_
_x000D_
_x000D_


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;}


_x000D_
_x000D_
input[type="radio"], input[type="checkbox"] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -1;_x000D_
}
_x000D_
_x000D_
_x000D_


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; 

}

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>

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;
}

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>`
    

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;
}

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 />

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 */

@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.


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 */

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>

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;}


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 */

@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.


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>

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>


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>

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?

Examples related to radio-button

Angular 4 default radio button checked by default Angular2 - Radio Button Binding Detect if a Form Control option button is selected in VBA How to create radio buttons and checkbox in swift (iOS)? How to check if a radiobutton is checked in a radiogroup in Android? Radio Buttons ng-checked with ng-model Multiple radio button groups in MVC 4 Razor Show div when radio button selected Check a radio button with javascript Bootstrap radio button "checked" flag