There is a parent div .main
contains two child div .child
. I have set the parent div as flex-wrap: wrap;
, but the child div are wrapped in the first place when the screen width is wide enough.
.main {
background-color: gray;
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
<div >
<div ></div>
<div ></div>
</div>
They should look like this at first
.main {
background-color: gray;
display: flex;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
width: 70%
}
.child:last-child {
width: 30%
}
<div >
<div ></div>
<div ></div>
</div>
And they should wrap when the screen width is so small
.main {
background-color: gray;
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
width: 100%;
}
<div >
<div ></div>
<div ></div>
</div>
CodePudding user response:
You can use a media query to tell it when to flex wrap. look what I did here:
@media screen and (max-width: 480px) {
.main {
flex-wrap: wrap;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
}
.main {
background-color: gray;
display: flex;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
width: 70%
}
.child:last-child {
width: 30%
}
<div >
<div ></div>
<div ></div>
</div>
CodePudding user response:
Just use a media-query to instruct the browser to use flex-wrap: wrap;
on .main
at your desired breaking point.
In this example, I set it to wrap
at 800px
.
.main {
background-color: gray;
display: flex;
flex-wrap: no-wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
@media only screen and (max-width: 800px) {
.main {
flex-wrap: wrap;
}
}
<div >
<div ></div>
<div ></div>
</div>
CodePudding user response:
to avoid media query, you may set a flex-grow value and a min-width. min-width set will trigger the wrapping .
example with a min-width set to trigger a break at about 700px:
.main {
background-color: gray;
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
/* average break point set at 700px
min-size at break point - 10px(gap padding/2) * 0.3 & 0.7 for each div*/
.child:first-child {
flex: 7 0 auto;
min-width: calc( 700px - (700px * 0.3) - 10px);
}
.child:last-child {
flex: 3 0 auto;
min-width: calc( 700px - (700px * 0.7) - 10px);
}
<div >
<div >Play me full page then resize the window to check my behavior</div>
<div ></div>
</div>