在两列中显示内容(每列 50%),如果内容不适合将列移至下一行并水平填充 space
Display content in two columns (50% each), if content does not fit move column to next row and fill horizontal space
在我的项目中,我想在两列中显示内容(每列 50%),如果内容不适合,则将列移到下一行并水平填充 space。
这里有两张图片来说明我的意思。
对于短文本,分两列显示:
当文本不再适合时,即任何一列的宽度都超过 50%,将第二列的内容移动到下一行以填充所有可用的水平 space。有点像这样:
这只能用 CSS 来完成吗?
您可以使用 flexbox
和 white-space: nowrap
堆栈片段
.wrapper {
display: flex;
flex-wrap: wrap;
margin-bottom: 10px;
}
.left,
.right {
flex: 1 0 50%;
background: lightgreen;
white-space: nowrap;
text-align: center;
padding: 10px;
box-sizing: border-box;
}
.right {
background: lightblue;
}
<div class="wrapper">
<div class="left">
This is a longer text. This is a longer text.
</div>
<div class="right">
This is a shorter text.
</div>
</div>
<div class="wrapper">
<div class="left">
This is an even longer text. This is an even longer text.
</div>
<div class="right">
This is a shorter text.
</div>
</div>
使用flex
是可以的。
看看我为你做的Fiddle。只需添加更多文本即可查看结果。
只需使用 flex-wrap
并对内容进行一些对齐和调整。
要使其在 cross-browser 环境中工作,请始终使用 Autoprefixer.
在我的项目中,我想在两列中显示内容(每列 50%),如果内容不适合,则将列移到下一行并水平填充 space。
这里有两张图片来说明我的意思。
对于短文本,分两列显示:
当文本不再适合时,即任何一列的宽度都超过 50%,将第二列的内容移动到下一行以填充所有可用的水平 space。有点像这样:
这只能用 CSS 来完成吗?
您可以使用 flexbox
和 white-space: nowrap
堆栈片段
.wrapper {
display: flex;
flex-wrap: wrap;
margin-bottom: 10px;
}
.left,
.right {
flex: 1 0 50%;
background: lightgreen;
white-space: nowrap;
text-align: center;
padding: 10px;
box-sizing: border-box;
}
.right {
background: lightblue;
}
<div class="wrapper">
<div class="left">
This is a longer text. This is a longer text.
</div>
<div class="right">
This is a shorter text.
</div>
</div>
<div class="wrapper">
<div class="left">
This is an even longer text. This is an even longer text.
</div>
<div class="right">
This is a shorter text.
</div>
</div>
使用flex
是可以的。
看看我为你做的Fiddle。只需添加更多文本即可查看结果。
只需使用 flex-wrap
并对内容进行一些对齐和调整。
要使其在 cross-browser 环境中工作,请始终使用 Autoprefixer.