Published at
Updated at
Reading time
1min

Last week I shared a #devsheet covering the CSS width properties min-content, max-content, and fit-content. I recommend having a look if you're not familiar with these CSS properties.

While reading about these underused properties, I discovered a neat pattern to build a centered navigation bar on CSS-Tricks.

The pattern uses fit-content to make the navigation take the exact amount of space to fit in all entries. The list container is then moved into the horizontal center using margin: 1em auto;.

ul {
  background: deepskyblue;
  padding: 1em;
  /* try to give the list as much space as needed */
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
  /* move the container to the center on the X-axis */
  margin: 1em auto;
}

li {
  display: inline-block;
  background: tomato;
  padding: .5em;
}

If you tried to give a centered navigation bar the exact fitting width paired with a background or border color, you might have already lost some hair on this problem.

Using fit-content is a beautiful solution, and I'm sure I'll reuse this pattern repeatedly in the future!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles