显示:Table-设置宽度的单元格/多行单元格

Display: Table-cell with set width/ cells on multiple lines

我有一系列 div,它们在移动设备中应该以页面宽度的 50% 显示。但是,它们也应该具有相同的高度(或者至少,每对两个相邻的 div 应该具有相同的高度)。我更愿意只使用 css 而不是 javascript 来执行此操作。这是我的初始代码:

<div class="box-container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
<div/>

.box-container{
    width:100%;
}
.box{
    width: 50%;
    float:left;
}

这给了我一盒 div,每行两个,但它们的高度不相等。所以我把它改成了 table:

.box-container{
    display:table-row;
}
.box{
    display:table-cell;
    float:none;
    position:relative;
    width: 50%;
}

但是,50% 的宽度似乎并不重要,所有的 div 都显示在同一行上。我怎样才能让它们各占 50% 并换行?

如果我正确理解您要实现的目标,您的第一个解决方案会更好。

使用浮动,不要忘记清除它们,框上的 height: 100% 也可以解决问题。

<div class="box-container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
<div/>

.box-container{
    width:100%;
}
.box-container:after {
  content: "";
  display: table;
  clear: both;
}
.box{
    width: 50%;
    float:left;
    height: 100%;
}

https://jsfiddle.net/Lmpx5w2s/1/

编辑。免责声明:这并没有具体回答如何使用 table 布局,但是由于 OP 的解决方案很灵活,所以这是我推荐的。

您的 div 高度不同的原因是因为您没有指定高度,它取决于其中的内容。您可以做很多事情,例如设置 min-heightmax-height 属性,甚至可以简单地设置 height 属性。但是,如果您不知道高度或 div 中可能包含的内容,您可以利用 flexbox。

尽管这不支持旧版浏览器,但这只是完成您的要求的一种方式:

.container {
  display: flex;
  flex-flow: row wrap;
  align-items: stretch;
  width: 100%;
}

.box {
  flex: 0 50%;
  background-color: green;
}

/*just for demonstration */
.box:nth-of-type(2) {
  background-color: blue;
}
.box:nth-of-type(3) {
  background-color: purple;
}
<div class="container">
  <div class="box">Box 1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
</div>

利用align-items: stretch:

Flex items are stretched such that the cross-size of the item's margin box is the same as the line while respecting width and height constraints.


参考文献:

flexbox