Search code examples
htmlcsscss-grid

CSS grid, centering 1 div, remaining divs on the next line


I'm trying to build some sort of pyramid in a parent div. I have 4 children divs. I want the first child to be centered. And the remaining divs underneath the first one (second row).

<style>
.parent {
   width: 100%;
   display: grid;
   grid-template-columns: repeat: (3, 1fr)
}
</style>
<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
</div>

I expect to have a result that looks like this: http://prntscr.com/orr41c


Solution

  • Here is what i did :

    /* first child goes in the first row / second column and span 1 column */
    
    .parent .child:nth-of-type(1) {
        grid-column: 2/ span 1;
        grid-row: 1;
        background: red;
      }
    
      /* the 3 other children place themselves in the second row */
    
      .parent .child:nth-of-type(n+2) {
        grid-row: 2;
      }
    

    <style>
      .parent {
        width: 150px;
        height: 100px;
        display: grid;
        grid-template-columns: repeat: (3, 1fr);
        margin: 0 auto;
      }
      
      .parent .child {
        background: yellow;
        width: 100%;
        height: 100%;
      }
      
      .parent .child:nth-of-type(1) {
        grid-column: 2/ span 1;
        grid-row: 1;
        background: red;
      }
      
      .parent .child:nth-of-type(n+2) {
        grid-row: 2;
      }
    </style>
    <div class="parent">
      <div class="child">1</div>
      <div class="child">2</div>
      <div class="child">3</div>
      <div class="child">4</div>
    </div>