Making a responsive CSS grid layout with just 3 properties
source link: http://www.js-craft.io/blog/making-a-responsive-css-grid-layout-with-just-3-properties/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
What if I told you that you only need to know only 3 CSS properties to make a fully responsive CSS grid like the one below:
Let's start with the HTML layout. Just a container and the divs corresponding to the articles and header + footer:
<div class="container"> <div class="header">Header</div> <div class="art first">Article 1</div> <div class="art second">Article 2</div> <div class="art third">Article 3</div> <div class="footer">Footer</div> </div>
First, we will need to set up our container to grid and add a bit of gap between the cells :
.container { display: grid; grid-gap: 10px; }
The most important part is made of defining the actual grid. If we would put this layout in an Excell table, it would look like this:
This can be translated into CSS by using the grid-template-areas
property:
.container { grid-template-areas: "h h h" "a1 a2 a3" "f f f"; display: grid; grid-gap: 10px; }
And now to place the HTML elements in the corresponding CSS grid cell we can use the grid-area
prop:
.header { grid-area: h; } .art.first { grid-area: a1; } .art.second { grid-area: a2; } .art.third { grid-area: a3; } .footer { grid-area: f; }
Making the CSS grid responsive
In order to make this one responsive, we can just change the table layout:
So a media query to and again grid-template-areas
to the rescue.
@media only screen and (max-width: 600px) { .container { grid-template-areas: "h" "a1" "a2" "a3" "f"; } }
We could have also used the display:block
, but the idea is just to show how flexible and useful grid-template-areas
can be to manage our layout configurations.
And that's all folks! Just 3 properties ( grid-area
, grid-gap
and grid-template-areas
) to make a fully responsive CSS Grid layout.
You can see below the full working codepen for this example. Cheers!
I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK