【问题标题】:Display: Table-cell with set width/ cells on multiple lines显示:设置宽度的表格单元格/多行单元格
【发布时间】:2018-05-15 18:41:23
【问题描述】:

我有一系列 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% 并换行?

【问题讨论】:

  • 您是否接受了使用表格布局的想法?使用 flex 有问题吗?
  • 不,我能做到,只是我对 flex 不太熟悉。我可以接受任何每行放置两个盒子并使每两个盒子高度相同的解决方案

标签: html css height css-tables tablerow


【解决方案1】:

编辑。免责声明:这并没有具体回答如何使用表格布局进行操作,但是由于 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

弹性项目被拉伸,使得项目的边距框的横向尺寸与线相同,同时遵守宽度和高度限制。


参考资料:

flexbox

【讨论】:

    【解决方案2】:

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

    使用浮点数,不要忘记清除它们,盒子上的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/

    【讨论】:

    • 我认为这行不通,因为我无法在容器上放置固定高度,高度取决于内盒的内容