Creating Responsive Layouts with CSS Grid
CSS Grid is a powerful tool for building highly responsive website designs. By combining the display property with CSS media queries, you can redefine your entire layout grid for specific screen sizes.
While Flexbox is excellent for one-dimensional layouts (a single row or a single column), CSS Grid is designed for two-dimensional layouts, giving you complete control over both rows and columns simultaneously.
Establishing the Grid Container
To use CSS Grid, you must define an outer container as a grid container. You do this by applying display: grid; to the parent container. You then define the number and size of the columns using the grid-template-columns property:
The 1fr unit is a special CSS Grid unit meaning "one fraction of the available space". Giving three columns a value of 1fr ensures they are all perfectly equal in width.
Making it Responsive with Media Queries
A layout with two or three columns usually becomes too cramped on smaller screens like tablets and mobile phones. To make the grid responsive, you can use a media query to simply overwrite the grid-template-columns property, reducing the number of columns.
Full Working Example
The approach in this example gives you total layout control at multiple breakpoints. Try viewing this example on a mobile device or resizing your browser to see the layout gracefully step down from three columns, to two columns, to a single column: