使用CSS网格自动调整列 [英] Auto-adjusting columns with CSS grid
问题描述
我正在尝试确定CSS网格是否能够像表格一样运作。
I'm trying to work out whether CSS grid is capable of behaving like a table.
因此,如果我有很长的单元格数据(col 2)并且表中其他地方都有可用空间,我不希望它像下面的图片一样进行包装:
So if I have a long piece of "cell data" (col 2) and there's space available elsewhere in the table, I don't want it to wrap as it does in the image below:
我想要实现的是这样的。内容较长的列会增加,而其他列会根据该列的内容而缩小。
What I want to achieve is something like this. Where the column with the longer piece of content grows and the other columns shrink based on the content in that column.
我在CodePen上上传了一个示例: https://codepen.io/anon/pen/WdNJdY
I've uploaded an example here on CodePen: https://codepen.io/anon/pen/WdNJdY
.wrapper {
display: grid;
grid-template-columns: 33.33% 33.33% 33.33%;
background-color: #fff;
color: #444;
max-width: 800px;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
<div class="wrapper">
<div class="box a">col 1</div>
<div class="box b">col 2</div>
<div class="box c">col 3</div>
<div class="box d">short data</div>
<div class="box e">a really long piece of data</div>
<div class="box f">short data</div>
</div>
我对CSS网格很陌生,所以我很好奇是否有可能。
I'm very new to CSS grid so I'm curious if this is possible.
我们对任何帮助表示感谢。
Any help is appreciated. Thanks in advance!
推荐答案
不要将列设置为33%...
Instead of setting your columns to 33%...
.wrapper {
display: grid;
grid-template-columns: 33.33% 33.33% 33.33%;
}
...设置固定宽度,每列使用可用空间:
... which sets a fixed width, have each column use available space:
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
然后,防止文字换行:
.box { white-space: nowrap; }
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
background-color: #fff;
color: #444;
max-width: 800px;
}
.box {
white-space: nowrap;
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
<div class="wrapper">
<div class="box a">col 1</div>
<div class="box b">col 2</div>
<div class="box c">col 3</div>
<div class="box d">short data</div>
<div class="box e">a really long piece of data</div>
<div class="box f">short data</div>
</div>
更多详细信息,请参见: CSS网格布局中百分比和fr单位之间的差异
More details here: The difference between percentage and fr units in CSS Grid Layout
这篇关于使用CSS网格自动调整列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!