DEV Community

Cover image for Flexbox and auto margins
Nicolas Erny
Nicolas Erny

Posted on

Flexbox and auto margins

When I started using flexbox, it seemed like my secret weapon to solve every layout problem. For example, centering elements become much easier. No need to use auto margins, the justify-content: center property does the job pretty well. But does it mean that auto margins are useless when we use flexbox?

Let's start with a basic website header containing a logo and two other links (contact and log in).

Website header example

Here's the HTML:

<div class="wrapper">
  <a href="" class="logo">My logo</a>
  <a href="" class="contacts">Contact</a>
  <a href="" class="login">Log in</a>
</div>
Enter fullscreen mode Exit fullscreen mode

Now, it's time to discuss styling.

Where to start?

The first idea is to use the justify-content: space-between property and let the logo element grow.

.wrapper {
  display: flex;
  gap: 1rem;
  padding: 1rem 3rem;
  justify-content: space-between;
}

.logo {
  flex: 1;
}
Enter fullscreen mode Exit fullscreen mode

At first glance, this solution looks perfect. But there is a significant drawback. The logo is a flex element that can grow (flex: 1) and consumes excess space to push the other links to the right side of the page. But our logo is a link. So it means that the space between the logo and the contact element is now clickable!

How to fix this issue?

The usual way is to wrap the right-sided links inside a div tag. Along with the justify-content: space-between property, the header works perfectly.

<div class="wrapper">
  <a href="">My logo</a>
  <div class="wrapper-links">
    <a href="" class="contacts">Contact</a>
    <a href="" class="login">Log in</a>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.wrapper {
  display: flex;
  gap: 1rem;
  padding: 1rem 3rem;
  justify-content: space-between;
}
.wrapper-links {
  display: flex;
  gap: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

What if I don't want to change the structure of the HTML code?

In this case, auto margins are very handy. Auto is a greedy property. It means that it can take all the available space. So, if I use margin-right: auto, it will push the logo as far away as possible from the other links.

<div class="wrapper">
  <a href="" class="logo">My logo</a>
  <a href="" class="contacts">Contact</a>
  <a href="" class="login">Log in</a>
</div>
Enter fullscreen mode Exit fullscreen mode
.wrapper {
  display: flex;
  gap: 1rem;
  padding: 1rem 3rem;
  justify-content: space-between;
}
.logo {
  margin-right: auto;
}
Enter fullscreen mode Exit fullscreen mode

I hope you found this trick helpful.
You can find the source code here.

Top comments (0)