Flex container layout items horizontally or vertically using the flex-direction
value of row
or column
respectively. By default, a flex container will try to fit its child elements on one line. Flexbox container might overflow if the size of items exceeds container size
Let’s look at below example to understand the problem
<div style={{ display: 'flex' }}> <div style={{ background: 'grey', padding: '10px' }}>Column One</div> <div style={{ background: 'orange', padding: '10px' }}>Column Two</div> <div style={{ background: 'purple', padding: '10px' }}>Column Three</div> <div style={{ background: 'darkblue', padding: '10px' }}>Column Four</div> <div style={{ background: 'skyblue', padding: '10px' }}>Column Five</div> <div style={{ background: 'navyblue', padding: '10px' }}>Column Six</div> <div style={{ background: 'pink', padding: '10px' }}>Column Seven</div> </div>
As we can see above the Column Seven does not fit within the container on the same row. Another, thing to notice is the text within the container automatically wraps - this happens because flex container tried to fit the items.
To fix this problem and automatically move the problematic item(s) on next row we have a flex-wrap
property that can be set to wrap
as follows
{ display: flex; flex-wrap: wrap; }
Let’s add this property to previous example
<div style={{ display: 'flex', 'flex-wrap': 'wrap' }}> <div style={{ background: 'grey', padding: '10px' }}>Column One</div> <div style={{ background: 'orange', padding: '10px' }}>Column Two</div> <div style={{ background: 'purple', padding: '10px' }}>Column Three</div> <div style={{ background: 'darkblue', padding: '10px' }}>Column Four</div> <div style={{ background: 'skyblue', padding: '10px' }}>Column Five</div> <div style={{ background: 'navyblue', padding: '10px' }}>Column Six</div> <div style={{ background: 'pink', padding: '10px' }}>Column Seven</div> </div>
See, how column five, column six, and column seven moved to the second row, and the text inside the columns is also displayed on a single line. Isn’t it awesome?
flex-wrap
also accepts other values i.e. wrap-reverse
and nowrap
(default)
wrap-reverse
behaves the same as a wrap but cross-start and cross-end are permuted.
I think flex-wrap
is great for responsive design as it will automatically wrap the content on the next row and you don’t have to worry about the responsive breakpoints.
Learn more about flex-direction
Like this article? Follow @devtutorialtips on Twitter