Preview Issue on JSBIN | View Issue Code on JSBIN
我正在使用 flexbox 来创建网格布局。大多数网格单元没有内容,一些网格单元确实有内容。当一个单元格有内容时,它会抛弃一切。 如何确保所有细胞均匀,无论内容如何?
我有三行,每行有三个单元格。只有中心单元格的中心行包含子项。
<div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div><span>contains span</span></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
在css中,中心空间比其他方块大。
body, html {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
body>div {
display: flex;
}
body>div>div {
border: solid 1px blue;
}
div {
flex-grow: 1;
}
body>div:nth-child(2)>div:nth-child(2) {
display: flex;
align-items: center;
justify-content: center;
}
答案 0 :(得分:11)
您应使用flex-basis
指定灵活项目的初始长度。
body, html {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
body>div {
display: flex;
}
body>div>div {
border: solid 1px blue;
}
div {
flex-grow: 1;
flex-basis: 80px; /*set the initial length*/
}
body>div:nth-child(2)>div:nth-child(2) {
display: flex;
align-items: center;
justify-content: center;
}
&#13;
<div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div><span>contains span asdsa asd asd asd asdsad ads asd sad</span></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
&#13;
答案 1 :(得分:11)
您正在使用flex-grow: 1
。这意味着flex项的初始宽度将是其内容的宽度,然后可用空间将平均分配。
但是,您希望弹性项具有相同的宽度,因此您希望忽略其内容的宽度。您可以使用
实现此目的flex: 1;
此外,Flexbox引入auto
作为min-width
的初始值。在某些情况下,这可能会产生不同的宽度,因此为了安全起见,最好添加min-width: 0
或将overflow
设置为visible
body,
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
body > div {
display: flex;
}
body > div > div {
border: solid 1px blue;
}
div {
flex: 1;
min-width: 0;
}
body > div:nth-child(2) > div:nth-child(2) {
display: flex;
align-items: center;
justify-content: center;
}
&#13;
<div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div><span>contains span</span></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
&#13;
答案 2 :(得分:2)
这只是设置33%flex-basis
body>div>div {
border: solid 1px blue;
flex: 0 0 33%;
}
body, html {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
body>div {
display: flex;
}
body>div>div {
border: solid 1px blue;
flex: 0 0 33%;
}
div {
flex-grow: 1;
}
body>div:nth-child(2)>div:nth-child(2) {
display: flex;
align-items: center;
justify-content: center;
}
&#13;
<div>
<div></div>
<div><span>contains span</span></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
&#13;