Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flexbox to wrap all or none

Tags:

html

css

flexbox

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;
}
like image 960
Daniel Armando Martinez Avatar asked Nov 15 '15 20:11

Daniel Armando Martinez


People also ask

How do you make a flexbox wrap?

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.

Why is my flexbox not wrapping?

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% .

What does the flex-wrap wrap rule do?

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.

Is flex-wrap responsive?

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.


1 Answers

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

like image 88
tungd Avatar answered Oct 17 '22 06:10

tungd