.container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
flex-direction: column;
}
.item {
margin: 10px;
border: 1px solid lightgray;
border-radius: 10px;
overflow: hidden;
width: 100%;
}
@media screen and (min-width:700px) {
.item {
width: 50%;
}
.container {
flex-direction: row;
}
}
<div class="container">
<div class="item">content</div>
<div class="item">content</div>
</div>
I was expecting a responsive design that when the screen is under 700px
, the items should be columnar and when the screen is wider than 700px
, the items should be in a row and their width should be 50%
. However, it looks like just width: 50%;
is applying.
This is the image:
2
Answers
You are using
min-width: 700px
which means that the styles inside the media query will apply when the screen width is at least 700px. However, you want the opposite: you want the styles to apply when the screen width is less than 700px. To do that, you need to usemax-width: 700px
instead.You are using
flex-direction: column
for the container, which means that the items will be stacked vertically. However, you want the opposite: you want the items to be stacked horizontally. To do that, you need to useflex-direction: row
instead.You need to change your media query and flex-direction values as follows:
You’d need to account for the
.item
elements’border-left-width
,border-right-width
,margin-left
andmargin-right
. In your code at viewport width greater than700px
, each.item
element takes up the following amount of horizontal space:Thus, for 2 items of
50% + 22px
width, this would be44px
greater than100%
, the width of.container
, and thus will continue to wrap at viewport width greater than700px
.To have them display in the same row, consider adjusting their
width
, compensating for the extra space from their horizontal border widths and horizontal margins by subtracting this extra space,22px
, from50%
:Alternatively, you could apply
flex-wrap: nowrap
on.container
. This forces the.item
elements to display in a row, by shrinking their widths to fit: