Useful Flexbox Technique: Alignment Shifting Wrapping

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

I just ran into a situation where I had a title that was split into two sections. The main title, big and bold, left-aligned like any regular title. But then a bit of a subtitle, right-aligned, sitting on the same line as the title. When there is room for that, it’s great. But of course text is always changing and the space you have available is variable. Let’s take a look.

This is the look we’re going for when there is room:

If there isn’t room based on screen size or length issues, left-aligned wrapping is what we want:

There are a bunch of ways to get that right-aligned text over there when there is room.

  • We could absolutely position it to the right. The main problem with that though, is that absolutely positioned elements are out of the document flow, so it can’t intelligently decide when to wrap against the other text. We’d have to specify some hard widths that we don’t want to in this case.
  • We could float it to the right. We don’t have to set widths that way and the text remains in the document flow, which is great. But, as soon as wrapping needs to happen, the text will remain hugged up toward the right, not nicely left aligned like we want.
  • We could make the thing a table, which allows us to put the text along the right edge with no trouble. But table cells don’t wrap at all so we can’t get the layout we’re looking for.

Thankfully flexbox can help us here! By making the title a flex container with display: flex; and the title itself flex-grow: 1;, it can push the subtitle all the way over to the right. Flex containers can wrap, so we’ll make sure that’s happening with flex-wrap: wrap;.

Here’s a video showing all the not-so-great methods and flexbox winning:

And a live demo:

See the Pen Wrapping Same-Line Titles by Chris Coyier (@chriscoyier) on CodePen.