使用浮动div实现表格单元格效果

时间:2010-10-26 21:00:44

标签: html css css-tables

如果我尝试将min-width,max-width应用于浮动div,以便在隐藏正确的内容时它扩展到max-width不起作用。

但是,如果我使用表和2 td。如果隐藏了右边的td,左边的td将扩展到100%。

我可以使用浮动div来实现此表格效果吗?

2 个答案:

答案 0 :(得分:0)

我认为你不能做你所要求的,但你可以让它看起来像你在问什么。

将其设为两个tds,并在td内的div上放置最大宽度。那会有用吗?

答案 1 :(得分:0)

这不适用于浮点数。幸运的是,我们现在拥有更多可用的工具。

这里有两种非常简单的方法,可将div扩展到可用宽度的100%(如果水平或水平的同级元素被隐藏或移除)。

#1 –使用display: flex

兼容性:Edge and all modern browsers. IE 10和11支持非标准的-ms-flexbox

基本标记

<div class="container">
  <div>
    First Column
  </div>
  <div>
    This second column can be hidden or not exist and the first column will take up its space
  </div>
</div>

CSS

  • 容器div被赋予display: flex

  • 为子容器分配flex: 1,它们将被分配相等的宽度,可以增长和可以收缩。

.container {
  width: 500px;
  display: flex;
}

.container>div {
  flex: 1;
  background: #FF6961;
  height: 200px;
  margin-bottom: 20px;
}

.container>div:nth-child(even) {
  background: #006961;
}
<div class="container">
  <div>
    Content
  </div>
  <div>
    Content
  </div>
</div>

<div class="container">
  <div>
    Content takes up the whole width when other divs are hidden.
  </div>
  <div style="display: none">
    Content
  </div>
</div>

<div class="container">
  <div>
    Content takes up the whole width when there is no other div.
  </div>
</div>

阅读this guide to flexbox

阅读more about flexbox on the MDN


#2 –使用display: table

兼容性: IE8+ and all modern browsers

基本标记

<div class="container">
  <div>
    First Column
  </div>
  <div>
    This second column can be hidden or not exist and the first column will take up its space
  </div>
</div>

CSS

  • 为容器指定了display: table
  • 容器子项的名称为display: table-cell,其作用与HTML表中的单元格相同。如果一个单元格被隐藏或被删除,另一个单元格将占用其空间。

.container{
  display: table;
  width: 600px;
  margin: 20px;
}

.container>div {
  display: table-cell;
  height: 200px;
  background: #FF6961;
}

.container>div:nth-child(even) {
  background: #006961;
}
<div class="container">
  <div>
    Content
  </div>
  <div>
    Content
  </div>
</div>

<div class="container">
  <div>
    Content takes up the whole width when other divs are hidden.
  </div>
  <div style="display: none">
    Content
  </div>
</div>

<div class="container">
  <div>
    Content takes up the whole width when there is no other div.
  </div>
</div>

<div class="container">
  <div>
    Content takes up the remaining width if a cell has a fixed width.
  </div>
  <div style="width: 200px">
    Content
  </div>
</div>

阅读more about CSS tables on the MDN