div多个浮动左伸展

时间:2011-05-09 15:30:36

标签: html width css-float

我喜欢这样:

<style>
 .putLeft
 {
   float: left;
 }
</style>

<table>
  <tr>
    <td>
      Some dynamic text
    </tr>
  </td>
  <tr>
    <td>
      <div id="div_1" class="putLeft">1<br/>2<br/>3<br/>4</div>
      <div id="div_2" class="putLeft">1<br/>2<br/>3<br/>4</div>
      <div id="div_3" class="putLeft">1<br/>2<br/>3<br/>4</div>
      <div id="div_4" class="putLeft">1<br/>2<br/>3<br/>4</div>
      <div id="div_n" class="putLeft">1<br/>2<br/>3<br/>4</div>
    </td>
  </tr>
</table>

div_1,div_2 ... div_n的内容是动态宽度的列。

我想要的是这样的:


|some text with dynamic width and can be very long text|
-------------------------------------------------------
|    div1   |      div2    |     div3    |     div4   |
|    1      |        2     |       2     |      4     |
|    1      |        2     |       2     |      4     |



But my result is something like this:

|some text with dynamic with and can be very long text|
-------------------------------------------------------
| div1 | div2 | div3 | div4 |
|  1   |   2  |   2  |   4  |
|  1   |   2  |   2  |   4  |

如何将“float:left”列拉伸到最大宽度?

注意:整个示例中没有固定宽度。我不能把桌子放在div的内容上。

编辑:在div上插入一些内容。我确实做了一些简单的例子。但它将有其他内容。

2 个答案:

答案 0 :(得分:1)

jQuery的例子是:

HTML:

<table>
  <tr>
    <td>
      Some dynamic text
    </tr>
  </td>
  <tr>
    <td id="row">
      <div id="div_1" class="putLeft"></div>
      <div id="div_2" class="putLeft"></div>
      <div id="div_3" class="putLeft"></div>
      <div id="div_4" class="putLeft"></div>
      <div id="div_n" class="putLeft"></div>
    </td>
  </tr>
</table>

CSS:

.putLeft
 {
   float: left;
    height: 20px;
    background: #ffcc33;
 }

table { width: 100% }

JS with jQuery

$(function() {
   var count = $('#row div').length;
   $('#row div').each( function(index, item) {
       $(item).css('width', Math.floor(100 / count) + '%');
   });
});

这是一个jsFiddle:http://jsfiddle.net/qdnvq/

通过从外部<td>检索'px'中的宽度,然后计算div的像素宽度,可以使得更精确,并且可以使最后一个更大以绕过丢失的空间来进行舍入。您也可以使用绝对定位而不是浮动。

答案 1 :(得分:0)

我为你开了一个小提琴并纠正你的加价:http://jsfiddle.net/yHrZx/
你能为它提供更多的HTML,以便我们可以帮助你使用CSS。 不惜一切代价避免使用JavaScript解决方案......