How do I align css grid items?
-
The values used for aligning will be similar to the ones we used to align using CSS flexbox.
The demo code used is:
CSS
... .container { width: 600px; background-color: rgb(95, 118, 133); margin: 40px auto; display: grid; grid-template-columns: repeat(2, 1fr); grid-template-rows: repeat(4, 100px); grid-gap: 30px; } .item { padding: 10px; font-size: 30px; color: #ffffff; } .item1 { background-color: plum; } .item2 { background-color: mediumvioletred; } .item3 { background-color: chocolate; } .item4 { background-color: darkgreen; } .item5 { background-color: firebrick; } .item6 { background-color: olivedrab; } .item7 { background-color: navy; } .item8 { background-color: yellow; } ...
HTML
... <div class="container"> <div class="item item1">item 1</div> <div class="item item2">item 2</div> <div class="item item3">item 3</div> <div class="item item4">item 4</div> <div class="item item5">item 5</div> <div class="item item6">item 6</div> <div class="item item5">item 7</div> <div class="item item6">item 8</div> </div> ...
The result is:
The CSS property justify-items is the first property to align grid items horizontally, the default is set to value stretch, the display does not change.
justify-items: start;
justify-items: end;
justify-items: center;
The CSS property align-items is the first property to align grid items vertically, the default is set to value stretch, the display does not change.
align-items: start;
align-items: end;
The CSS properties justify-self and align-self work the same way as the above properties but work on individual grid items.
© Lightnetics 2024