AtoZ CSS Quick Tip: Float and Clear and Centering Elements
Buying a SitePoint Premium membership will give you access to the full AtZ: CSS series.
Welcome to our AtoZ CSS series! In this series, I’ll be exploring different CSS values (and properties) each beginning with a different letter of the alphabet. In this article I’ve added a new quick tip/lesson about the Float and Clear properties and how to center elements in all sorts of ways.
F is for Float and Clear
Floating is great if you want to move an element to the left or right of a page, but unfortunately, you can’t do float: center
to center an element. What a pain right?
Well, never fear, here’s the low down on centering all sorts of elements.
Tip 1
If the element is a block element, you can combine width
and margin: auto
.
margin: auto
will automatically calculate the margins on the left and right sides, so they’re both equal, centering the block within its containing element.
See the Pen tip-margin-auto by SitePoint (@SitePoint) on CodePen.
Tip 2
If the element is inline (or inline-block), use text-align: center
on the parent container.
See the Pen tip-flexbox by SitePoint (@SitePoint) on CodePen.
Tip 3
If the element is absolutely positioned, combine left
and transform
to center the element horizontally.
See the Pen tip-flexbox by SitePoint (@SitePoint) on CodePen.
A similar technique can also be used to vertically center elements, but more on that in a future tip!
Tip 4
Use flexbox (another ‘F’ property, yay!)
To use flexbox to center a single item (or group of items) you need to set two properties on the containing element: display: flex
and justify-content: center
.
See the Pen tip-flexbox by SitePoint (@SitePoint) on CodePen.
There are plenty of other cool things you can do with flexbox including growing or shrinking a containing element to best use the available space. You can even align an element both vertically and horizontally as opposed to blocking and inline which dictate either vertical or horizontal alignment.
Another great benefit of using flexbox is that there is no longer an issue with collapsing containers and the need to use a clearfix solution.