Search code examples
cssformsradio-buttoninline

Radio Buttons Inline and Centered with Labels


I have the following form:

        <form action="post.php" method="POST">
            <fieldset>
                 <div class="ratingClass">
                      <input type="radio" class="radio" name="rate" value="1" id="1"/>
                      <label for="1">1</label>
                      <input type="radio" class="radio" name="rate" value="2" id="2"/>
                      <label for="2">2</label>
                      <input type="radio" class="radio" name="rate" value="3" id="3"/>
                      <label for="3">3</label> 
                      <input type="radio" class="radio" name="rate" value="4" id="4"/>
                      <label for="4">4</label>
                      <input type="radio" class="radio" name="rate" value="5" id="5"/>
                      <label for="5">5</label>                                                                
                 </div>
            </fieldset>
            <input type="submit" value="Rate">
        </form>

Styled by the following CSS:

fieldset { 
 overflow:hidden; 
}
.ratingClass { 
 float:left; 
 clear:none;
}
label { 
 float:left; 
 clear:none; 
 display:block; 
 padding: 2px 1em 0 0; 
}
input[type=radio], input.radio { 
 float:left;
 clear:none; 
 margin: 2px 0 0 2px; 
}

It's all inside of another div that has text-align: center; styling.

I realize that behavior is because of the floats, but if I remove them then the radio buttons no longer display inline.

How can I have them inline and centered?


Solution

  • You don't need to float everything nor make the labels block elements. Replacing your CSS with this causes everything to be centered:

    fieldset {
      overflow: hidden;
    }
    label {
      padding: 2px 1em 0 0;
    }
    input[type=radio], input.radio {
      margin: 2px 0 0 2px;
    }
    

    The <div class="ratingClass"> is also superfluous and can be removed.