How to create a responsive grid in CSS
Grid is a layout in CSS that helps us achieve a design having a 2D grid containing rows or columns. It is a better way to arrange the elements of our HTML document instead of using conventional positioning properties. We can create a responsive grid layout to easily adjust the CSS of our grid with our screen's display size.
Creating a responsive grid
In this answer, we will learn how to create a responsive grid in CSS. We can make our grid responsive by using a media query.
Media query
A media query in CSS allows us to apply styles to our HTML document based on specific conditions, such as the screen size or device type. The responsiveness we achieve using it ensures a better and more friendly user experience.
Syntax
Syntax for media query is as following:
@media media-type and (condition) {/* We apply styles here which executes when the condition is met */}
@media: It is a keyword that refers to using a media query.media-type: It means the type of media the we target, such asscreen,print,speech, orall. If we leave this space empty it is set toallby default.condition: It means the condition that has to be true so the code inside the media query block is executed.
For example:
@media screen and (max-width: 600px) {/* We apply styles here which executes when the condition is met */}
In this example, the media-type is screen while the condition is max-width: 600px.
Coding example
In the following example, we will create a responsive grid layout.
Let's understand the code first.
<head> tag:
Lines 4–6: We define the title for our HTML document.
<style> tag:
Lines 9–16: We create a grid layout with one column and four rows for our
gridContainer. Each row has the same height with a definedgap. Then we set thewidthandheightof thegridContainer.Lines 18–23: We set the styling for each
gridItem.Lines 25–31: Our media query is applied when the height of the viewport is at least
300px. There is nomedia-typespecified so that means media query will be applied to all media types. We modify thegridContainerclass to have two columns and two rows with equal width and height, respectively using1frfor each. Then we adjust theheightof the grid container.
<body> tag:
Lines 35–40: We create a parent container called the
gridContainer. Then we create four grid items with the classgridItem.
Run the example
Let's run the example now:
When our viewport container has height
200px(less than300px). Our media query is not applied as its condition is false.
When our viewport container has height
400px(greater than300px), our media query is applied as its condition is true.
Conclusion
A responsive grid in CSS lets us adjust our grid layout according to different screen sizes and devices. We can use media queries to make our grid layout responsive. Responsive grids enhance our website's usability and responsiveness.
Free Resources