首页 > 解决方案 > 显示:设置宽度的表格单元格/多行单元格

问题描述

我有一系列 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 每行两个,但它们的高度不相等。所以我把它改成了一张桌子:

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

但是,50% 的宽度似乎并不重要,所有的 div 都显示在同一行。我怎样才能让他们每个人都是 50% 并打破一个新的路线?

标签: htmlcssheightcss-tablestablerow

解决方案


编辑. 免责声明:这并没有具体回答如何使用表格布局进行操作,但是由于 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 项目被拉伸,使得项目的边距框的横向大小与线相同,同时尊重宽度和高度限制。


参考:

弹性盒


推荐阅读