Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make radio group labels display nicely inline with radio buttons using pure CSS

Tags:

html

css

Previously I used a table to display radio buttons with labels. Now I am trying to do this same thing using only CSS.

this was made using a table

What can I do in CSS that will make the label text sit nicely on top of the related radio button? This is the HTML:

<div class="controls">
    <label class="radio">
        <input type="radio" name="cfimb_5" id="id_cfimb_5_1" value="1">
        Never
    </label>
    <label class="radio">
         <input type="radio" name="cfimb_5" id="id_cfimb_5_2" value="2">
    </label>
    <label class="radio">
        <input type="radio" name="cfimb_5" id="id_cfimb_5_3" value="3">
        Sometimes
    </label>
    <label class="radio">
        <input type="radio" name="cfimb_5" id="id_cfimb_5_4" value="4">
    </label>
    <label class="radio">
        <input type="radio" name="cfimb_5" id="id_cfimb_5_5" value="5">
        Frequently
    </label>
</div>

Here is a codepen: http://codepen.io/anon/pen/keuhl

like image 303
broinjc Avatar asked Jan 11 '23 05:01

broinjc


1 Answers

Historically, you could use margins to achieve this layout:

.controls label {
    display: inline-block;
    width: 90px;
    height: 20px;
    text-align: center;
    vertical-align: top;
    padding-top: 40px;
}
.controls input {
    display: block;
    margin: 0 auto -40px;
}
<div class="controls">
  <label class="radio">
    <input type="radio" name="foo" value="1">
    Never
  </label>
  <label class="radio">
     <input type="radio" name="foo" value="2">
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="3">
    Sometimes
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="4">
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="5">
    Frequently
  </label>
</div>

On modern browsers that support flexbox, the solution is considerably easier:

.controls {
  display: flex;
}

.radio {
  flex: 1 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="controls">
  <label class="radio">
    <input type="radio" name="foo" value="1">
    Never
  </label>
  <label class="radio">
     <input type="radio" name="foo" value="2">
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="3">
    Sometimes
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="4">
  </label>
  <label class="radio">
    <input type="radio" name="foo" value="5">
    Frequently
  </label>
</div>
like image 158
Etheryte Avatar answered Jan 25 '23 17:01

Etheryte