When you use CSS to float an element that does not have an explicit width, the element’s width becomes its “shrink-to-fit” width. This is useful when you’re floating elements that you don’t know how wide they need to be. A very common example is a navigation bar, where you often want the width of the links to vary depending on how much text they contain.
Not knowing an element’s width makes it harder to center it horizontally, however. Take the navbar example. What if you have a list of a few items, you want them to shrinkwrap, but you also want to shrinkwrap and center the whole navbar horizontally? Shrinkwrapping it is easy – you just need to float it. But centering is not quite that straightforward. You can try margin:0 auto;
, but unless you give the navbar an explicit width it won’t do anything. And that’s the problem – you don’t know how wide the navbar is.
If you could specify float:center
that would probably do the trick. Sadly you can’t do that (not yet anyway). Fortunately there are several other ways to solve this problem.
Posted in CSS.
Copyright © Roger Johansson