DEV Community

Cover image for Create a dynamic grid/layout using CSS variables.
Yogesh Devaliya
Yogesh Devaliya

Posted on • Updated on

Create a dynamic grid/layout using CSS variables.

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Then we will create a .grid class in CSS.

CSS

.grid {
  display: grid;
  grid-template-columns: var(--col);
  grid-template-rows: var(--row);
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
sonangrai profile image
Sonahang Rai

:)

Collapse
 
sforest1975_52 profile image
sforest1975

this knowledge can use in gird-template?
i tried but not work. my problem or unable?