/blog/articles/

Centered fluid width navigation with floating links thanks to fit-content

We all know the problem that an element, that contains floating elements can't be centered with `margin: 0 auto;` because it has no real width. But there is something coming our way that will change this situation for the better: `fit-content`

Just apply `fit-content` to the container of floating elements and oh see, you can use `margin: 0 auto;`

<div class="container">
    <ul class="list-centered">
        <li>Lorem ipsum</li>
        <li>li>Dolor sit amet</li>
        <li>li>Constetetur</li>
    </ul>
</div>
.container {
    width: 600px;
}

.list-centered {
    margin: 0 auto;
    width: -webkit-fit-content;
       width: -moz-fit-content;
            width: fit-content;
}

.list-centered li {
    float: left;
}

Browser support is, as one could expect, poor at the moment but the cool things always start out like that. So if you know you're only building for Chrome and Firefox you can go ahead and use it right now.

I made a CodePen to show it in action:

``Check out this Pen!
Martin Wolf

Hi, I’m Martin Wolf, a Freelance Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.