开发者

Equidistant radio buttons across div

I'm trying to span a dynamic amount of radio buttons across the entire width of a div without the use of tables (if possible). I don't want a clump of them to the left of the div, the right, or the middle, but I want them equally spaced along the width, with whitespace the same on either side of every single button.

<div style='width:100%开发者_运维知识库'>
  <input type="radio">
  <input type="radio">
  <input type="radio">
  <input type="radio">
</div>

Can this be done in CSS? If not, is the best alternative to use a table?


This won't work in < IE8. You could provide a conditional comment stylesheet fallback, perhaps by floating them.

Example

Equidistant radio buttons across div

HTML

<div id="container">
    <div><input type="radio"></div>
    <div><input type="radio"></div>
    <div><input type="radio"></div>
    <div><input type="radio"></div>
</div>

CSS

#container {
    display: table;  
    width: 100%;
}

#container div {
    display: table-cell; 
    text-align: center;
} 

jsFiddle.

Test it by adding new elements.


You may also want to try this version as well since it is a bit flexible if you decide to add more radios later on and it works on any browser thanks to jQuery. Yeah, I know, JavaScript for presentation purposes...{shutter}!

<script>
$(document).ready(function(){
    // get width of containing div
    var width = $('#radios_group').width();
    // get the number of radios in this group
    var count = $('#radios_group input[type=radio]').length
    // width of each element (take 5 extra pixels off to account for variations)
    var radio_width = parseInt(width / count) - 5;

    // loop over each radio and set it to the new width
    $('#radios_group input[type=radio]').each(function(){
        $(this).width(radio_width);
    });
});
</script>

<div id="radios_group" style='width:100%'>
  <input type="radio">
  <input type="radio">
  <input type="radio">
  <input type="radio">
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜