4

I've started to learn grid system (display:grid) and I have the following code, but I don't know how to center last two columns (4 and 5) without add more columns in grid-template-columns and use grid-column-start and grid-column-end in the columns. Is it possible?:

HTML:

<div class="grid-container">
  <div class="grid-item">
      1
    </div>
    <div class="grid-item">
        2
    </div>
    <div class="grid-item">
        3
    </div>
    <div class="grid-item">
        4
    </div>
    <div class="grid-item">
        5
    </div>
</div>

CSS:

body {
    margin: 0;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;
}

.grid-item {
    padding: 10px;
    background: skyblue;
}

JSFiddle: https://jsfiddle.net/3b5Lxujh/

What I have:

What I have

What I want:

What I want

kukkuz
  • 41,512
  • 6
  • 59
  • 95

1 Answers1

3

You should add columns if you are using CSS girds - you use a 6-column grid for this using grid-template-columns: repeat(6, 1fr) with each item spanning two grid columns - and place the last row to the center by using grid-column rule - see demo below:

body {
  margin: 0;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 20px;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  grid-column: span 2;
}

.grid-item:nth-last-child(2) {
  grid-column: 2 / 4;
}

.grid-item:last-child {
  grid-column: 4 / 6;
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>

Flexbox Solution

For this layout flexbox is more suited - and normally I'd use a flexbox using flex-basis (with calc to create the grid gaps) like this:

body {
  margin: 0;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  margin: 10px;
  flex-basis: calc(33.33% - 40px);
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • I was in the middle of writing this exact same code for an answer when you posted this. Should the `grid-column` line be removed or what is that for? – dmikester1 Mar 16 '19 at 18:34
  • The only thing I couldn't figure out which is not a big issue is how to remove the outer margins from the outer divs in each row. Maybe not possible when creating gaps this way with margins. – dmikester1 Mar 16 '19 at 18:35
  • 1
    a *hack* is to give `margin: 0 -20px` to remove the outer margins and then handle overflow on the parent of `grid-container`... – kukkuz Mar 16 '19 at 18:38