Hi! with CSS grid we can easily create a card component in few lines of code and its responsive to let's check it out
HTML structure
This is our main container. inside our main container, we have a card container
our HTML is ready now we copy and paste this card container for two more times.
Here is the Fun part (CSS)
Give basic and default stylings(i used SCSS here).after that
in our main container, we give display: grid;
to our main container and specifiying column witdh and count grid-template-columns: repeat(auto-fit,300px);
with row and column gap ofgap:1rem
grid-template-columns
gtc determines the column width for each child of the grid parent. the repeat function repeats the size for each number of columns. I know what you're thinking what is auto-fit? I will explain this later. now we style our cards
Cards styling
I applied few styles to our cards. now we will look our result
RESULT
Magic... Our card components are ready no more coding. ok now we will learn about autofit
Auto fit
Auto-fit takes up the as much as the width that available in the grid. I will explain this with an example. for this now we change auto-fit to 3 columns and add a background for visualization
Three columns result
when we mention the number of columns it takes up the width according to the grid container size. now we change the viewport size.
so it is a fixed width. you can change the number columns according to the viewport in media queries
Now using auto-fit
If you want a responsive card component then use auto-fit.
Magic.. and additional there's an auto-fill too here difference between auto-fill and fit. auto-fit vs auto-fill
Controlling height using grid-auto-rows
Normally grid set a row height based on the content but sometimes content for each card may differ so we can control the height using grid-auto-rows. For clear explaination about auto-rows
codepen
Top comments (0)