The other day I read a good article on horizontal centering by Roger Johansson in where he explains the shrinkwrapping effect. Basically, it’s about one of the most common problems you can find in the wild, namely how to center a navigation bar that contains floated elements with undefined widths.
As we all know, centering this kind of stuff can be quite tricky sometimes. With this common example in mind, Roger made an awesome list with solutions you can apply in order to achieve horizontal centering.
Just another possible approach
Recently, I found out that Firefox and Chrome both support intrinsic widths and one of the most interesting values for
width seems to be the
fit-content one. Also, in this article, you’ll see how
fit-content can be a solution for solving the problem above.
Apparently, just as on tables, when you only need to add
auto for left and right margins to center it horizontally, setting the
width: fit-content to an element tells the browser the element’s width is defined by its content and will not automatically size to fill its containing block.
width: fit-content example
Now, with Roger’s markup example:
and the following CSS lines:
… you just got a new experimental solution for centering horizontally a navigation bar that contains floated elements within. Pretty straightforward, huh? Don’t forget to check the demo’s page source to see the full styles.
Minimal browser support
Despite the poor browser support at this time (Chrome and Firefox), this might be a good alternative to keep in mind for the future. Just think about the CSS Flexbox module, in the beginning, the support was quite minimal and now it’s getting wider and wider.
Also, you should be aware that
fit-content value is kinda experimental and it’s not a final recommendation. It’s available in W3C Editor’s Draft and that means that specs might change in the future.
Animenu - a responsive dropdown navigation made with SASS
Thoughts on becoming a better developer