I recently join a web app project. I was tasked with making some parts of the web responsive to mobile view. The Homepage consists of a grid with three columns:
.main {
font-family: "Gentona 300";
height: 100vh;
width: 100%; /* Set height to 100% of viewport height */
display: grid;
overflow: hidden;
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: 1fr 0.2fr 2fr 2fr;
grid-template-areas:
"sidebar header header"
"sidebar navbar navbar"
"sidebar main main"
"sidebar main main";
}
I used media queries to change the layout into a single column like this:
.main {
font-family: "Gentona 300";
height: 100vh;
width: 100%; /* Set height to 100% of viewport height */
display: grid;
overflow: hidden;
grid-template-columns: 1fr;
grid-template-rows: 1fr 0.2fr 2fr 2fr;
grid-template-areas:
"header"
"navbar"
"main"
"main";
}
@media screen and (min-width: 768px) {
.main {
grid-template-columns: 1fr 3fr 1fr;
grid-template-areas:
"sidebar header header"
"sidebar navbar navbar"
"sidebar main main"
"sidebar main main";
}
}
Is this the correct way to do it?
2
Answers
Your approach is correct.
But you can shorten the code by combining
grid-template-areas
,grid-template-columns
andgrid-template-rows
togrid-template
property:Your approach would work as it is valid but "poorly" coded. Yru let elements span 2 rows or 2 columns while in the end it should be just 1.
You say you have a 3-column grid such as:
As you see, you actually have only a 2-column grid as the aside is the left column and header, nav, and main all span 2 columns and as such are actually only 1 column:
The same applies for rows. You let the main span 2 rows while the row height is by default auto and as such only as height as the content. So you can shorten it as welll to:
Your CSS should be: