我正在尝试在CSS中创建网格布局。我想在网格上方放置标题。我希望页眉的左边缘与网格中第一项的左边缘对齐。我创建了我的网格的一个片段。了解如何拖动网格的容器以调整其大小时网格元素与容器边缘之间的宽度不相同。
如何使标题与网格元素的最左边缘对齐?
编辑:当有多余的水平空间时,我希望网格项目居中。设置justify-content: left;
不是解决方案。
.page {
min-width: 300px;
background: lightgray;
padding: 12px;
resize: horizontal;
overflow: auto;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 140px);
grid-column-gap: 12px;
grid-row-gap: 12px;
width: 100%;
justify-content: center;
}
.grid-element {
color: #fff;
overflow: hidden;
height: 82px;
background: white;
}
<div class="page">
<p>Grid Header</p>
<div class="grid">
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div>
</div>
答案 0 :(得分:0)
您可以给它一个类,然后使用边距对齐它。
答案 1 :(得分:0)
将justify-content: flex-start;
添加到.grid
类,希望这对您有所帮助。谢谢
.page {
min-width: 300px;
background: lightgray;
padding: 12px;
resize: horizontal;
overflow: auto;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 140px);
grid-column-gap: 12px;
grid-row-gap: 12px;
width: 100%;
justify-content: flex-start;
}
.grid-element {
color: #fff;
overflow: hidden;
height: 82px;
background: white;
}
<div class="page">
<p>Grid Header</p>
<div class="grid">
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div>
</div>
答案 2 :(得分:0)
我只需将标题添加为跨越所有第一行的网格内的元素
.page {
min-width: 300px;
background: lightgray;
padding: 12px;
resize: horizontal;
overflow: auto;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 140px);
grid-column-gap: 12px;
grid-row-gap: 12px;
width: 100%;
justify-content: center;
}
.grid-element {
color: #fff;
overflow: hidden;
height: 82px;
background: white;
}
.grid p {
grid-row:1;
grid-column:1/-1;
}
<div class="page">
<div class="grid">
<p>Grid Header</p>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div class="grid-element"></div>
<div>
</div>