AtoZ CSS Quick Tip: Float and Clear and Centering ElementsBy Guy Routledge
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. We know that sometimes screencasts are just not enough, 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.
If the element is a block element, you can combine
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.
If the element is inline (or inline-block), use
text-align: center on the parent container.
If the element is absolutely positioned, combine
transform to center the element horizontally.
A similar technique can also be used to vertically center elements, but more on that in a future tip!
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
More from this author
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.