DEV Community

Cover image for # Create Card Components using css grids

# Create Card Components using css grids

・2 min read

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

main container

This is our main container. inside our main container, we have a card container
card 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


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

card stylesI applied few styles to our cards. now we will look our 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

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.
resizeso 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 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

Discussion (0)

Forem Open with the Forem app