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.
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.
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 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 as screen
, print
, speech
, or all
. If we leave this space empty it is set to all
by 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
.
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 defined gap
. Then we set the width
and height
of the gridContainer
.
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 no media-type
specified so that means media query will be applied to all media types. We modify the gridContainer
class to have two columns and two rows with equal width and height, respectively using 1fr
for each. Then we adjust the height
of the grid container.
<body>
tag:
Lines 35–40: We create a parent container called the gridContainer
. Then we create four grid items with the class gridItem
.
Let's run the example now:
When our viewport container has height 200px
(less than 300px
). Our media query is not applied as its condition is false.
When our viewport container has height 400px
(greater than 300px
), our media query is applied as its condition is true.
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