How to right align grid elements
P粉296080076
P粉296080076 2023-08-13 11:27:01
0
1
501

I have a fixed number of columns in a CSS Grid layout and have elements to be placed in these columns. The number of elements to be placed is less than the number of columns.

I want the columns to be aligned to the right, in the order the elements were added. In the following code, there are 4 elements aligned to the left with 6 empty elements to the right:


.hello { border-style: solid; border-color: blue; } .container { display: grid; grid-gap: 5px; grid-template-columns: repeat(10, 5rem); }
1
2
3
4


I want to change the layout above to:

empty empty empty empty empty empty 1 2 3 4

I tried various combinations of [align,justify]-[content,items], but none of them achieved the effect of right alignment. Can CSS Grid achieve this?

P粉296080076
P粉296080076

reply all (1)
P粉208469050

Due to the limited number, you can define them manually

.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}
1
2
3
4
1
2
3
1
2
3
4
5
6

But it’s better to use 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}
1
2
3
4
1
2
3
1
2
3
4
5
6
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!