Yogesh Devaliya
Posted on August 18, 2021
You can create a layout in many ways. Using Grid Or Flex to create a layout is more advanced and customizable.
If your layout is dynamic and complex then you can use this approach to design your layout instead of creating the custom classes.
Traditional approach:
Let's assume that you want to create a layout like a cover image.
For that you have to create a custom class like this:
HTML
<div class="custom-grid-1"></div>
<div class="custom-grid-2"></div>
CSS
.custom-grid-1 {
display: grid;
grid-template-columns: 1fr 1fr 2fr;
grid-template-rows: auto;
}
.custom-grid-2 {
display: grid;
grid-template-columns: 3fr, 1fr;
grid-template-rows: auto;
}
Now, instead of creating multiple classes for the layout, we will create a single grid class that will have a dynamic CSS variables to set the fractional unit(fr) and other properties.
In HTML, we will set the variable values in the style attribute.
HTML
<div class="grid" style="--col: 1fr 1fr 2fr; --row: auto;"></div>
<div class="grid" style="--col: 3fr 1fr; --row:auto;"></div>
Then we will create a .grid class in CSS.
CSS
.grid {
display: grid;
grid-template-columns: var(--col);
grid-template-rows: var(--row);
}
By using this approach you can create any dynamic & complex grid/layout without creating a multiple classes.
Same way you can assign any properties in the grid class using CSS variables.
Share your thoughts in comment section.
Posted on August 18, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.