Search code examples
htmlcsscss-grid

Can I get content to appear in the middle column of a CSS Grid layout with only one div?


If I have a 3 column grid and I want the content to appear in the 2 column: am I understanding correctly that the content HAS to go in the 2nd column in the HTML, and I have to create an empty div in the HTML?

In the grid below I want the title to appear in the middle column so I've created an empty div before this.

There's no way of getting the title to appear in the middle one of the 3 columns whilst only using one div is there?

** Note I haven't included a div for the 3rd column because I don't need to.

Codepen: https://codepen.io/emilychews/pen/rEoKPg

Code snippet also included below.

body {
  margin: 0;
  padding: 0;
  display: flex;
  height: 100vh;
  width: 100%;
  justify-content: center;
  align-items: center;
}

.row {
  width: 50%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 1rem;
}

.grid {
  background: #f1f1f1;
  padding: 1rem;
}
<div class="row">
  <div class="grid grid-item-1"></div>
  <div class="grid grid-item-2">The Title</div>
</div>


Solution

  • You don't have to create an empty div if you use grid-column-start, but you will need to specify the column number.

    <div class="row">
      <div class="grid grid-item-2">The Title</div>
    </div>
    
    body {
      margin: 0;
      padding: 0;
      display: flex;
      height: 100vh;
      width: 100%;
      justify-content: center;
      align-items: center;
    }
    
    .row {
      width: 50%;
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 1rem;
    }
    
    .grid {
      background: #f1f1f1;
      padding: 1rem;
    }
    
    .grid-item-2 {
      grid-column-start: 2;
    }