A use case for margin in css flexbox

submited by
Style Pass
2025-01-08 21:00:05

While working through Josh Comeau's CSS course (highly recommended - review coming soon), I came across a helpful technique to build simple layouts.

In this post, I'll walk through four different ways to align a basic header layout (the one using margin is number 4). Fair warning: this isn't exactly groundbreaking work! But it does help build an intuition that saves time on frontend work later on.

We're writing a header for a website. It has links to different sections, with the logo linking to the 'home page'. Here's the HTML for our header, with navbar a flex container:

There's just one issue with this: the empty space created by flex: 1 is clickable, which feels awkward - especially on wider screens where the space is large.

This works, but with an edge case when the flex container uses gap: on smaller screens, the spacer shrinks to zero but the gap is still applied to both sides of the spacer. This doubles the spacing and makes the layout overflow on screens where it should comfortably fit.

Leave a Comment