假设我们有一个响应式网格容器,其中的子单元格数量不确定。单元的宽度和高度会有所不同。仅使用CSS(可能是CSS网格),我们如何创建这样的网格,即根据容器的大小(不溢出)和单元格的大小动态确定列/行的数目以及每一列/行的宽度/高度。以下两种方式之一:
当应用于列宽时,这两种情况大致对应于表的自动和固定布局算法。除了我们不知道列和行的数量,需要以某种方式自动确定。
以下示例说明了这两种情况适用于列宽的情况。对于每种情况,都有两种可能的流向:行或列。请注意,在示例中,我们必须专门设置列数及其大小。我希望这些是自动确定的。
请尝试在您的答案中复制这些示例,而不设置确切的列数,行数以及任何宽度或高度。
* {
box-sizing: border-box;
}
.container {
display: grid;
flex-wrap: wrap;
grid-template-rows: repeat(3, auto);
justify-content: space-between;
border: 3px solid teal;
font-size: 20px;
}
.flex {
grid-template-columns: repeat(3, auto);
width: min-content;
}
.fixed {
grid-template-columns: repeat(3, 33.33%);
width: 28em;
}
.column {
grid-auto-flow: column;
}
.cell {
padding: 1em;
background: pink;
border: 1px dashed teal;
white-space: nowrap;
}
h3:not(:first-of-type) {
margin-top: 3em;
}
<h3>Flexible column width. Flow in rows</h3>
<div class="container flex row">
<div class="cell">One</div>
<div class="cell">Two</div>
<div class="cell">Buckle my shoe</div>
<div class="cell">Three</div>
<div class="cell">Four</div>
<div class="cell">Knock at the door</div>
<div class="cell">Five</div>
<div class="cell">Six</div>
</div>
<h3>Flexible column width. Flow in columns</h3>
<div class="container flex column">
<div class="cell">One</div>
<div class="cell">Two</div>
<div class="cell">Buckle my shoe</div>
<div class="cell">Three</div>
<div class="cell">Four</div>
<div class="cell">Knock at the door</div>
<div class="cell">Five</div>
<div class="cell">Six</div>
</div>
<h3>Fixed column width. Flow in rows</h3>
<div class="container fixed row">
<div class="cell">One</div>
<div class="cell">Two</div>
<div class="cell">Buckle my shoe</div>
<div class="cell">Three</div>
<div class="cell">Four</div>
<div class="cell">Knock at the door</div>
<div class="cell">Five</div>
<div class="cell">Six</div>
</div>
<h3>Fixed column width. Flow in columns</h3>
<div class="container fixed column">
<div class="cell">One</div>
<div class="cell">Two</div>
<div class="cell">Buckle my shoe</div>
<div class="cell">Three</div>
<div class="cell">Four</div>
<div class="cell">Knock at the door</div>
<div class="cell">Five</div>
<div class="cell">Six</div>
</div>
答案 0 :(得分:0)
使用列时,我遇到了同样的问题,此问题已通过在父元素中添加grid-template-columns: repeat(auto-fit, minmax(baseValue,maxValue));
来解决。