我正在尝试使用CSS网格创建一个表,基于内容使用相等的列。我想避免使用<table>
。这是这个问题的后续行动:Auto-adjusting columns with CSS grid
我想要实现的目标:
此表有效:https://codepen.io/anon/pen/baExYw
但我想把每一行包裹在div
中,这不足为奇地打破了桌子。
这张桌子坏了:https://codepen.io/anon/pen/qpbMgG
app.html
<div class="wrapper">
<div class="box a">col 1</div>
<div class="box b">col 2</div>
<div class="box c">col 3</div>
<!-- Table Row -->
<div class="row">
<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>
<!-- Table Row -->
<div class="row">
<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>
</div>
app.css
.wrapper {
display: grid;
grid-template-columns: repeat(3, auto);
background-color: #fff;
color: #444;
max-width: 800px;
}
.box {
background-color: #444;
color: #fff;
border-radius: 5px;
padding: 20px;
font-size: 150%;
}
我对CSS Grid还是一个新手,所以我仍然无法理解这些东西中有一半是在幕后工作的。
任何帮助表示赞赏。提前致谢。
在你的first example中,你的数据单元是容器的子代。因此,网格属性 - which only work between parent and child - 按预期工作。
在你的second example中,你有一些数据单元是.row
容器的子代。这些细胞不再是网格容器.wrapper
的孩子。因此,这些单元格不在网格布局的范围内,不识别网格属性并呈现为标准块级元素。
因此,基本上,具有不同子元素的网格容器呈现不同的布局。
让您的示例匹配的一个解决方案是将网格项目放入具有与父项相同属性的网格容器中。这是一般的想法:
.wrapper {
display: grid;
grid-template-columns: repeat(3, minmax(50px, 1fr));
background-color: #fff;
color: #444;
max-width: 800px;
}
.row {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(3, minmax(50px, 1fr));
}
div:nth-child(4) { grid-row-start: 2; }
div:nth-child(5) { grid-row-start: 3; }
.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>
<!-- Table Row -->
<div class="row">
<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>
<!-- Table Row -->
<div class="row">
<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>
</div>
它没有破坏,它完全按照预期工作。每个子元素都使用网格的一个单元格,如果您将标题包装在另一个div中,您将看到它们为列交换行,因为每个组将使用一个单元格。
如果要显示表格数据,那么您应该坚持使用表格,因为它们是用于此目的的语义正确的元素。
但是,如果您正在尝试构建响应式设计或者您真的想要使用网格,我建议您使用read this关于CSS网格的令人难以置信的文章。
看看display: subgrid;
也许这就是你在这个场景中寻找的东西。