how to keep radio-button or checkbox and its label together when content wraps in flow layout

Tim picture Tim · Feb 2, 2013 · Viewed 18.5k times · Source

How to keep the radio button ( ) or checkbox [ ] and its label together when text wraps as the browser window is made narrower, so that we don't end up with this:

          [ ] pepperoni   [ ] anchovies   [ ] mushrooms    [ ]
          olives

EDIT in response to nowrap suggestions. Thanks for the suggestion. Almost there. It works perfectly in Chrome, FF, and Opera but not in IE9. When the page CSS is label {white-space: nowrap} and the markup is:

          <td>
          <div>
          <label>
          <input type="radio" name="pizza" checked="true" 
           id="pepperoni" value="pepperoni"  />pepperoni  </label>
          <label>
          <input type="radio" name="pizza"  
           id="anchovies" value="anchovies"  />anchovies  </label>
           <label>
          <input type="radio" name="pizza" 
           id="mushrooms" value="mushrooms"  />mushrooms  </label>
          <label>
          <input type="radio" name="pizza" 
           id="olives" value="olives"  />olives           </label>
          </div>
          </td>

the TD becomes fixed-width in IE9; the TD won't shrink when the browser window is made narrower, and I get this:

         ( ] pepperoni   ( ) anchovies   ( ) mushrooms   ( )  olives

when I need this:

          ( ) pepperoni   ( ) anchovies   
          ( ) mushrooms   ( ) olives

Is there any additional trick for IE9? I tried putting a span containing a single space between the labels: ...</label><span> </span><label>... but that did not work.

Answer

Sirko picture Sirko · Feb 2, 2013

Surround both with a <span> container and set white-space: nowrap; on it.

<span style="white-space: nowrap;"> 
  <input type="checkbox" id="in1" /> 
  <label for="in1">pepperoni</label>
</span>
<span style="white-space: nowrap;"> 
  <input type="checkbox" id="in2" /> 
  <label for="in2">anchovies</label>
</span>
<span style="white-space: nowrap;"> 
  <input type="checkbox" id="in3" /> 
  <label for="in3">mushrooms</label>
</span>
<span style="white-space: nowrap;"> 
  <input type="checkbox" id="in4" /> 
  <label for="in4">olives</label>
</span>

EDIT

As mentioned by @xiaoyi, you could also use the <label> itself as the container:

<label style="white-space: nowrap;"> <input type="checkbox" />  pepperoni</label>
<!-- etc -->