Useful Flexbox Technique: Alignment Shifting Wrapping | CSS-Tricks (original) (raw)

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.

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.