TIL How to Center a Div Independently of its Size

Today I learned how to center a div or img on a page without relying on its predetermined width or height. First, if you don’t care about centering the object vertically, the best method I’ve found is as follows:

.centered { margin: auto; }

But to center it horizontally and vertically, I had always used the following method (assume a div of height:500px; width:500px;):

.centered { position:relative; top:50%; left:50%; margin-top: -250px; margin-left: -250px }

This centers the object’s top left corner and uses negative margins to completely center it. However, it relies on hard coding half the height and width. But researching a bit further, I found another novel way to center an object in a container. The following method does not rely on knowing the height or width of the object. This saves you the hassle of not having to edit additional CSS if you decide to change the height or width of the centered object later. It goes as follows, using an img in this example:

.container { height:100%; text-align:center; }
span { height:100%; vertical-align:middle; display:inline-block; }
img { width:500px; vertical-align: middle; }

The height of the img can be anything you want, I just made it 500px wide in this example. And the img is the adjacent sibling of the span, both of which are children of the container. Credit goes to Wex. See his solution and JSFiddle here.

Leave a Reply

Wordpress theme JaeDubya © 2019 | All Right Reserved | Designed & coded by J. Arthur Wetenkamp