Reputation: 12729
I made a demo in which I make a 1 by 4 grid; 1 row and 4 columns. It's working fine, but I want it to display a 2 by 2 grid when the user screen is less than 720px
. I tried to use media query like this:
body, * {
padding: 0;
margin: 0;
}
.wrapper {
display: flex;
}
.box {
height: 100px;
border: 1px solid;
box-sizing: border-box;
flex: 1;
background-color: grey;
}
@media only screen and (min-width: 360px) and (max-width: 720px) {
.box {
background-color: blue;
}
}
How can change my layout when screen size is less than 720px?
Bin: https://jsbin.com/xudihuxato/edit?html,css,output
Upvotes: 2
Views: 3636
Reputation: 370993
@media only screen and (min-width: 360px) and (max-width: 720px) {
.wrapper {
flex-wrap: wrap;
}
.box {
flex-basis: 34%;
background-color: blue;
}
}
In your primary code you have the flex items set to flex: 1
. This is the shorthand equivalent to:
flex-grow: 1
flex-shrink: 1
flex-basis: 0
Essentially, this takes the entire space on the row and divides it up equally among the four items.
To make the items break into a 2x2 grid, set the following rules in the media query:
Allow the items to wrap with flex-wrap: wrap
. The default is nowrap
.
Set the flex-basis
to 50%, so only two items can fit on each row.
If you want to make space for borders, padding and/or margins, set the flex-basis
to 34% (or something like that).
With flex-grow: 1
defined in the main rule, there's no need for flex-basis
to be 50%, which may result in one item per row due to the borders, padding or margins.
Since flex-grow
will consume free space on the row, flex-basis
only needs to be large enough to enforce a wrap.
In this case, with flex-basis: 34%
, there's plenty of space for the margins, but not enough space for a third item on each line.
Upvotes: 1