跨越div的等距单选按钮

时间:2011-03-18 05:34:12

标签: html css alignment

我正在尝试在不使用表格的情况下在div的整个宽度上跨越动态数量的单选按钮(如果可能)。我不希望它们在div的左边,右边或中间有一堆,但是我希望它们沿着宽度等间隔,每个按钮的两边都有相同的空白。

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

这可以在CSS中完成吗?如果没有,是使用表格的最佳选择吗?

2 个答案:

答案 0 :(得分:9)

这不适用于&lt; IE8。您可以通过浮动它们来提供条件注释样式表回退。

实施例

Example

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

答案 1 :(得分:0)

你可能也想尝试这个版本,因为如果你决定稍后添加更多的无线电,它有点灵活,并且它可以在任何浏览器上运行,这要归功于jQuery。是的,我知道,JavaScript用于演示目的...... {快门}!

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