Using a CSS Grid for Even Row Element Spacing

Ole Ersoy
Nov 6, 2023
Image by julia roman from Pixabay

Scenario

We have 3 div elements contained in a CSS Grid and each div takes up the entire width of the container.

We want the div to be spaced out by 36px without using margins. This is the markup.

    <div class="GridRowSpacer">
<div class="div1">div1</div>
<div class="div2">div2</div>
<div class="div3">div3</div>
</div>

Approach

To achieve this we will configure our grid as follows.

.GridRowSpacer {
display: grid;
grid-template-columns: 1fr;
grid-gap: 36px;
width: 100%;
}

Demo

The div elements are given variable heights as follows.

.div1 {
background-color: aqua;
height: 50px;
}
.div2 {
background-color: orange;
height: 100px;
}

.div3 {
background-color: blue;
height: 150px;
}

And the elements will have 36px between them horizontally.

--

--