我在 CSS 网格显示中有固定数量的列,以及要放入这些列中的元素。要放置的元素数量小于列数。
我希望列按照添加元素的顺序向右对齐。在下面的代码中,4 个元素左对齐,另外 6 个元素右对齐:
.hello {
border-style: solid;
border-color: blue;
}
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(10, 5rem);
}
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
<div class="hello">4</div>
</div>
我想更改上面的显示:
1 2 3 4 empty empty empty empty empty empty
到
empty empty empty empty empty empty 1 2 3 4
我尝试过各种
[align,justify]-[content,items]
的组合,但从来没有找到正确的组合。这可以通过 CSS 网格实现吗?
由于数量有限,您可以手动定义全部
.hello {
border-style: solid;
border-color: blue;
}
.container {
display: grid;
gap: 5px;
grid-template-columns: repeat(10, 3rem);
margin: 5px;
}
.container > :nth-last-child(1) {grid-column-end: -1}
.container > :nth-last-child(2) {grid-column-end: -2}
.container > :nth-last-child(3) {grid-column-end: -3}
.container > :nth-last-child(4) {grid-column-end: -4}
.container > :nth-last-child(5) {grid-column-end: -5}
.container > :nth-last-child(6) {grid-column-end: -6}
.container > :nth-last-child(7) {grid-column-end: -7}
.container > :nth-last-child(8) {grid-column-end: -8}
.container > :nth-last-child(9) {grid-column-end: -9}
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
<div class="hello">4</div>
</div>
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
</div>
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
<div class="hello">4</div>
<div class="hello">5</div>
<div class="hello">6</div>
</div>
但是最好使用flexbox:
.hello {
border-style: solid;
border-color: blue;
width: 3rem;
}
.container {
display: flex;
gap: 5px;
width: calc(10*3rem + 9*5px);
margin: 5px;
}
.container > :first-child {margin-left:auto}
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
<div class="hello">4</div>
</div>
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
</div>
<div class="container">
<div class="hello">1</div>
<div class="hello">2</div>
<div class="hello">3</div>
<div class="hello">4</div>
<div class="hello">5</div>
<div class="hello">6</div>
</div>