html - 显示 : Table-cell with set width/cells on multiple lines

标签 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% 并换行?

最佳答案

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

关于html - 显示 : Table-cell with set width/cells on multiple lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50357183/

相关文章:

javascript - 如何使自动加载进度条重定向?

JQuery Accordion ,根据高度定位页脚

javascript - 取消选择 DOM 元素

html - css 链接没有使所有文本成为链接?

css - 在不触发响应式样式 css 的情况下放大浏览器

swift - 更改单元格高度但不更改其中的元素

html - 设置底部 CSS 属性时,CSS 溢出滚动条定位错误

javascript - 如何在 JavaScript (JQuery) 中构建 "big"div 结构?

html - 如何以编程方式向 Google 搜索提供站点结构和 url 路径

css - Zurb 基础 Accordion CSS 断点