Is there a way to achieve the following?
Starting with three items on a single row, if the total width exceeds the flex parent's width, snap to a column orientation.
The major constraint on a solution for my particular use case is that I am unable to use media queries to swap the flex-direction although this would probably be the easiest thing to do.
Media queries aren't a viable solution this case because the component is stand-alone and can be placed in a variety of locations which will dictate the container width independently of the browser width. If there is some magic whereby media queries can be based on a parent container rather than the page, that would be awesome, but I haven't seen anything like that so far.
In this fiddle the second div with longer names needs to be wrapped into three lines, but the closest I can get is two lines.
<div class="container">
<span class="item">Dan Martinez </span>
<span class="item">@DanMartinez101 </span>
<span class="item">an hour ago </span>
</div>
<br/>
<div class="container">
<span class="item">Someone with a really long name </span>
<span class="item">@AndAReallyLongHandle </span>
<span class="item">about three million years ago </span>
</div>
.container {
display: flex;
flex-wrap: wrap;
width: 400px;
background-color: 'red';
}
.item {
white-space: nowrap;
flex: 0 1 auto;
}
Making things wrap If you want to cause them to wrap once they become too wide you must add the flex-wrap property with a value of wrap , or use the shorthand flex-flow with values of row wrap or column wrap . Items will then wrap in the container.
If you are using flexbox and want the content to wrap, you must specify flex-wrap: wrap . By default flex items don't wrap. To have the images be three-across, you should specify flex-basis: 33.33333% .
The flex-wrap CSS property sets whether flex items are forced onto one line or can wrap onto multiple lines. If wrapping is allowed, it sets the direction that lines are stacked.
The flex-wrap property is a quick way to make parent elements more responsive on various screen sizes. As with flexbox in general, it simplifies page layouts so you don't have to manually set breakpoints or manage the page overflow yourself.
The problem can be solve with container queries. However none of the browser vendors implemented it (the spec is not finalized, AFAIK).
In the mean time you can use a polyfill: https://github.com/mlrawlings/containerqueries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With