Flexbox Force Wrap

Glenn Blog Leave a Comment

Using Flex Box is a modern and highly effective way to create responsive web site with fluid layouts. As modern browsers support the CSS flex property there are few drawbacks other than it not playing nicely in older browsers and/or Internet Explorer 11. Sometimes though you may want to force a break / new line in a flex layout (in the same order) purely for design purposes, so for example you may want to show less items on a top row than on the second row. That goes against the flexbox natural layout, as usually you would have the row with the lesser number of items on the bottom.

Example

On a recent client site we wanted 6 items on the first line and 7 on the second and we wanted this to happen ‘Cross Browser‘.

Natural Flex

The natural flex without a break would display like:-

Flexbox Force Wrap flex no wrap

So we have more items (1) on the top row, but what we want to see is:-

Flex Wrap

A flex wrap after the 7th item so that we get an initial 2 rows with one more item on the top row:-

Flexbox Force Wrap flex wrap

The Flex Wrap Code

Yes there are ways to force a wrap with

flex-wrap: wrap;

… but we found the only way to ensure a flex wrap in an out of sequence order Cross Browser is to physically insert a ‘flex-basis’ 100% div that forces a break at a specific point and this is how you do it:-

Script

$( document ).ready(function() {
$('.services-item:nth-of-type(6)').after('<div class="break"></div>');
});

CSS

.break {
flex-basis: 100%;
  width: 0px; 
  height: 0px; 
  overflow: hidden;
  display: inline-block; 
  }
/* Remove Break on Mobiles for natural Flex */
@media screen and (max-width: 479px) {
.break {display: none;}
}

So what the code does is insert a .break div after the 6th item to force a break/new line after that item, pushing the other items to the next line out of the usual flow (as per the second of the above images)

Note: You don’t have to use script to insert the .break div if you prefer to hard code it manually. In our case the items were being dynamically created and so the script was able to interrupt the html output to allow for the break.

About the Author
Flexbox Force Wrap 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced Web Designer / Web Developer (Webflow, WordPress, Weebly & Custom), Front-end / Back-end Developer & New Media Specialist, with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries, built up over a number of years.