Responsive Design Tips: Always use flex-wrap: wrap on flex containers

I spent a bit of time this morning make some improvements to sqlite.directory, and I found myself needing to make a number of fixes around the mobile responsiveness of the UI. So, I thought I would take a moment to catalog a few common patterns and tips I have found useful when working with responsive design. This first tip was one that I found myself using quite a bit today.


I use flex containers a ton; I love them. But, I find myself overlooking the same responsive detail time and time again—I don’t properly handle wrapping. Let’s take a real example from the sqlite.directory header:

See the Pen responsive design tip: flex-wrap (before) by Stephen Margheim (@smargh) on CodePen.

As you can see, on a smaller screen, the website title/logo and the user info are smashed together. Just ugly. I fixed this issue in this commit where I made these two simple changes:

-<header class="w-full max-w-6xl mx-auto py-4 mb-4 text-lg flex justify-between items-center border-b">
- <h2 class="flex items-center gap-2">
+<header class="w-full max-w-6xl mx-auto py-4 mb-4 text-lg flex justify-between items-center flex-wrap gap-y-2 border-b">
+ <h2 class="flex items-center gap-2 whitespace-nowrap">
<%= link_to root_path, class: "group" do %>
<%= image_tag "/icon.svg", class: "inline-block" %>
<code class="">
<span class="text-blue-500 group-hover:underline decoration-blue-500">sqlite</span>
<span class="inline-block group-hover:animate-bouncing -mx-3">.</span>
<span class="text-black group-hover:underline decoration-black">directory</span>
</code>
<% end %>
</h2>
 
- <div class="inline-flex items-center gap-2">
+ <div class="ml-auto inline-flex items-center gap-2">

The result speaks for itself:

See the Pen responsive design tip: flex-wrap (after) by Stephen Margheim (@smargh) on CodePen.

Let’s break down the changes precisely:

  1. Add flex-wrap gap-y-2 to the <header> flex container
  2. Add whitespace-nowrap to the <h2> containing the website title/logo
  3. Add ml-auto to the <div> containing the user info

The first change is the most important. By adding flex-wrap to the flex container, we allow the children to wrap to the next line when the container is too small. This is a simple change that can make a big difference in the responsiveness of your UI.

Next, we simply manage the wrapping more elegantly. We tell the website title/logo to not wrap its text with whitespace-nowrap, and we tell the user info to always sit to the right with ml-auto.

All combined, we get a much more pleasant mobile experience. I hope this tip helps you as much as it has helped me. Happy coding!