I have the following template:
<div id="row">
<div id="longer"></div>
<div id="shorter"></div>
</div>
When they are in the same row, i would like longer
to take twice as much width as shorter
, so I've applied the following CSS:
#row {
display: flex;
flex-wrap: wrap;
}
#longer {
flex: 1 0;
}
#shorter {
flex: 0.5 0;
}
This seemingly works fine, but when shorter
is wrapped, it takes only 50% of the new row, even though it's the only item in that row.
I would like shorter
to fill the entire row, if it's the only item in that line.
Is this possible to achieve without media queries?
In cases where the sum of children's flex-grow
value is less than 1, they will not fill the entire parent's width, and only the corresponding fraction instead.
You can just multiply them up by the same scale so they are at least 1:
#row { display: flex; flex-wrap: wrap; } #longer { flex: 2 0; } #shorter { flex: 1 0; } /* Just for demo */ #row div { white-space: nowrap; } #row div:nth-child(1) { background: green; } #row div:nth-child(2) { background: red; }
<div id="row"> <div id="longer">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> <div id="shorter">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> </div>
Make it flex: 2 0
and flex: 1 0
- fractional flex-grow
or flex-shrink
will only flex a fraction of the available space in the flex axis . See demo below:
body { display: flex; } #row { flex: 1 0; display: flex; flex-wrap: wrap; } #longer { flex: 2 0; background-color: lightgreen; } #shorter { flex: 1 0; background-color: lightblue; }
<div id="row"> <div id="longer"> this_is_the_longer_div_asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd </div> <div id="shorter"> this_should_fill_parent_width_when_wrapped </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.