Grid Love
05 March, 2021 - 3 min read
I must admit, I struggle with what is so-called responsive when it comes to web development. You have to fit or even re-design your containers and divs subject to each device, oh lord, you have to write multiple media queries and keep track of all the transformation. Until I found the grid, I was like at the “ah ha” moment. So let me tell you why grid excites me alot.
So, we often have a bunch of card-like sections, where you have repeated formats: a photo, a description under the photo. What you usually want is to stack these cards on top of each other on small devices and to display these in rows of two or three on bigger devices.
<div class="grid-container">
<div class="grid-item">
<div class="content">
<img src="1.jpg" />
<p class="date">April 01, 2020</p>
<h3>Moonlight</h3>
<p class="desc">Lorem ipsum dolor sit amet 2</p>
</div>
</div>
<div class="grid-item">
<div class="content">
<img src="2.jpg" />
<p class="date">April 02, 2020</p>
<h3>Cloudy Day</h3>
<p class="desc">Lorem ipsum dolor sit amet 2</p>
</div>
</div>
</div>
Inside the grid-container selector put these lines:
.grid-container {
width: 100%;
margin: 2em auto 0;
padding: 2em 2em;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
/* Grid */
display: grid;
grid-gap: 1em;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
}
.grid-item {
background: #ffffff;
border-radius: 1em;
margin-bottom: 2em;
padding: 1.5em;
width: 80%;
color: black;
margin-left: 0.5em;
/* Grid */
display: grid;
grid-template-columns: 1fr;
align-items: center;
}
First we need to declare we are going to display the children of the container in grid style (display: grid). But alone, this line of code will not do anything on its own. Then we define the number of columns the grid-container will hold. Usually you will need to specify how many and for which width. But as we try to make it responsive on its own depending on the size of the viewport, we will use “repeat”, “auto-fit” and “minmax”. Inside “repeat” we need 2 parameters. Firstly is how many times to repeat. Secondly is the width value of one unit/grid-item. If we want to have one column, we will write: repeat(1, 1fr) or repeat (1, 100px), or if we want two columns and each has a width of 200px as repeat (2, 200px).
Auto-fit: allow overflow of column to the next row to if it does not fit into the available space Minmax(min-value, max-value): in our code minimum width for our column is 320px or 1 fractional unit. Fractional unit means the available space on the viewport or the width so to say.
So together they work like a harmonica, stretching and shrinking harmonically. Cool right, they set their own break points. You can change around the min and max value to experiment how your content looks to fit your needs.
Here are some links to dig in further: