15

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&nbsp;</span>
    <span class="item">@DanMartinez101&nbsp;</span>
    <span class="item">an hour ago&nbsp;</span>
</div>

<br/>

<div class="container">
    <span class="item">Someone with a really long name&nbsp;</span>
    <span class="item">@AndAReallyLongHandle&nbsp;</span>
    <span class="item">about three million years ago&nbsp;</span>
</div>

.container {
    display: flex;
    flex-wrap: wrap;
    width: 400px;
    background-color: 'red';
}

.item {
    white-space: nowrap;
    flex: 0 1 auto;
}

1 Answers1

2

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

tungd
  • 14,467
  • 5
  • 41
  • 45