显示:表格单元格,多行设置宽度/单元格

时间:2018-05-15 18:41:24

标签: html css height css-tables tablerow

我有一系列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%并突破新线?

2 个答案:

答案 0 :(得分:1)

修改即可。免责声明:这并没有具体说明如何使用表格布局,但是由于OP对解决方案很灵活,我建议这样做。

你的div高度变化的原因是因为你没有指定高度,这取决于它内部的内容。您可以执行许多操作,例如设置min-heightmax-height属性,甚至只需设置height属性。但是,如果您不知道高度或者div中可能包含的内容,您可以利用flexbox。

虽然这不支持旧浏览器,但这只是实现您的要求的一种方式:

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

利用align-items: stretch

  

Flex项目被拉伸,使得项目边距框的横截面尺寸与线条相同,同时考虑宽度和高度限制。

参考文献:

flexbox

答案 1 :(得分:0)

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

使用花车,不要忘记清除它们,框上的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/