我正在创建一个有三列的网格。每个网格框都有一个div,其内部的最大宽度为280px
,有时网格列比此宽。我想对齐网格框中的内容,使左列与左对齐,中间列与中心对齐,右列与右对齐。请参阅下图,了解我想要的结果:
目前我在网格容器元素上使用CSS justify-items: justify
规则。我的当前结果如下:
如何使用CSS在我想要的布局图中生成布局?
答案 0 :(得分:2)
您可以使用CSS Grid,但(据我所知),您必须使用grid-columns
属性定位特定justify-self
上的项目并根据需要对齐它们。
特殊情况是只有一个项目的行。
.container {
display: grid;
grid-gap: 1rem;
grid-template-columns: repeat(3, 1fr);
}
.item {
width: 100px;
height: 300px;
background: pink;
}
.item:nth-of-type(3n) {
justify-self: end;
}
.item:nth-of-type(3n + 2) {
justify-self: center;
}
.item:nth-of-type(3n + 1):last-of-type {
grid-column: 2;
justify-self: center;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
答案 1 :(得分:2)
最简单的解决方案是使用item
选择器使nth-child
33%宽,然后向左,中心和右对齐每个列的内容。
为此,您可以使用inline-block
或flex
等,在第一个示例中我使用了Flexbox。
Stack snippet
.flex {
display: flex;
flex-wrap: wrap;
}
.flex .item {
width: calc((100% / 3) - 10px);
border: 1px dotted black;
box-sizing: border-box;
margin: 5px;
display: flex;
}
.flex .item:nth-child(3n+2) div {
margin: 0 auto; /* center align every 3rd, start from item 2 */
}
.flex .item:nth-child(3n+3) div {
margin-left: auto; /* right align every 3rd, start from item 3 */
}
.flex .item div {
max-width: 280px;
padding: 20px;
background: lightgray;
}
&#13;
<div class="flex">
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
</div>
&#13;
对于那些需要支持不支持Flexbox(或有错误行为)的浏览器的人,这个使用inline-block
和float
.parent::after {
content: '';
display: block;
clear: both;
}
.parent .item {
float: left;
width: calc((100% / 3) - 10px);
border: 1px dotted black;
box-sizing: border-box;
margin: 5px;
}
.parent .item:nth-child(3n+2) {
text-align: center; /* center align every 3rd, start from item 2 */
}
.parent .item:nth-child(3n+3) {
text-align: right; /* right align every 3rd, start from item 3 */
}
.parent .item div {
display: inline-block;
max-width: 280px;
padding: 20px;
background: lightgray;
text-align: left;
}
&#13;
<div class="parent">
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
<div class="item">
<div>Some content that can be max 280px wide</div>
</div>
</div>
&#13;
答案 2 :(得分:1)