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:

    01d1d38c-62bc-4744-9e6b-86e35ee2cc64-image.png

    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;

    130bae38-880b-4e2e-910f-b7dc54c1a570-image.png

    justify-items: end;

    45e15f79-af03-4501-9a51-8e6657a7f9f7-image.png

    justify-items: center;

    d2b53ed2-112e-472f-b8dc-c9ea63823eca-image.png

    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;

    fe58830f-f369-41cf-8779-4440239f5bfb-image.png

    align-items: end;

    40c9dd05-b18d-4ff8-805f-ddbc616b7e6c-image.png

    The CSS properties justify-self and align-self work the same way as the above properties but work on individual grid items.


Log in to reply
 

© Lightnetics 2024