我玩了一些flexboxes,并试图模仿一个类似LaTeX的桌子,顶部/中间/底部.我喜欢桌子很好地缩放并转移到小屏幕上的列表式显示.
但是,我注意到,如果我在单元格的文本内容中使用空格,则单元格的高度可能会增加一倍甚至三倍而没有任何明显的原因.
是否有一个我忽略的flexbox属性可以帮助我解决这个问题?为什么这个额外的高度甚至会产生?
片段:
div.table {
display: flex;
flex-flow: column wrap;
width: 70%;
margin: 15px auto;
border-bottom: 2px solid black;
}
div.row {
display: flex;
justify-content: space-between;
flex-flow: row wrap;
}
div.head {
flex: 1;
text-align: center;
align-items: flex-start;
font-weight: bold;
border-width: 2px 0 1px;
border-style: solid;
}
div.item {
flex: 1;
text-align: center;
align-items: flex-start;
}
<div class="table">
<div class="row">
<div class="head">Col 1</div>
<div class="head">Col 2</div>
</div>
<div class="row">
<div class="item">Cell 1</div>
<div class="item">Cell2</div>
</div>
<div class="row">
<div class="item">Cell 3</div>
<div class="item">Cell 4</div>
</div>
</div>
最佳答案 问题是,最初,.row的大小只考虑.items的内容.然后.items弯曲,并由于弯曲变得同样宽:1.但内容不是同样宽,所以最长的将包裹到第二行.
在这个例子中更好地显示:
.row {
display: inline-flex;
margin: 2px;
}
.item {
border: 1px solid;
}
.flex {
flex: 1;
}
<div class="row">
<div class="item">Cell 11111</div>
<div class="item">Cell 2</div>
(before flex)
</div>
<br />
<div class="row">
<div class="item flex">Cell 11111</div>
<div class="item flex">Cell 2</div>
(after flex)
</div>
在您的示例中,您有Cell 1(带空格)和Cell2(不带),这会产生差异.
最终.row也会弯曲,因此不再需要换行,但似乎浏览器没有检测到.这很难说,但我认为这是对的.那是因为
>计算行的hypothetical main size(高度),并且
If a cross size is needed to determine the main size (e.g. when the
flex item’s main size is in its block axis) and the flex item’s cross
size is auto and not definite, in this calculation use fit-content as
the flex item’s cross size.
> Rows flex.这决定了他们的使用高度.
> Cross sizes (widths) are determined.行被拉伸以水平填充表格.但为时已晚,已计算出高度.
由于.table具有自动高度,因此列布局不会换行,我只使用默认的flex-wrap:nowrap.它解决了这个问题,因为现在flex容器将是单行的,因此行的宽度将为definite:
If a single-line flex container has a definite cross size, the outer
cross size of any stretched flex items is the flex container’s inner
cross size (clamped to the flex item’s min and max cross size) and is
considered definite.
div.table {
flex-flow: column;
}
div.table {
display: flex;
flex-flow: column;
width: 70%;
margin: 15px auto;
border-bottom: 2px solid black;
}
div.row {
display: flex;
justify-content: space-between;
flex-flow: row wrap;
}
div.head {
flex: 1;
text-align: center;
align-items: flex-start;
font-weight: bold;
border-width: 2px 0 1px;
border-style: solid;
}
div.item {
flex: 1;
text-align: center;
align-items: flex-start;
}
<div class="table">
<div class="row">
<div class="head">Col 1</div>
<div class="head">Col 2</div>
</div>
<div class="row">
<div class="item">Cell 1</div>
<div class="item">Cell2</div>
</div>
<div class="row">
<div class="item">Cell 3</div>
<div class="item">Cell 4</div>
</div>
</div>
您还可以尝试显式提供显式宽度:
div.row {
width: 100%;
}
甚至阻止使用空格进行文本换行:nowrap.