
This is a handy trick that I’ve been using a lot lately that is definitely something you should keep in your toolbox. It’s really a simple trick that works and has great browser support.
Here’s all you need to know about how to vertically center a div within a div:
.outsidebox { height:200px; width:200px; background:blue; position:relative; } .insidebox { height:50px; width:50px; background:red; position:absolute; top:50%; transform:translateY(-50%); -webkit-transform:translateY(-50%); }
And this keeps things centered with dynamic div heights too.
Or an alternative horizontal centering, use the following CSS:
.outsidebox { height:200px; width:200px; background:blue; position:relative; } .insidebox { height:50px; width:50px; background:red; position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); }
Simple enough, right?
Anthony Montalbano
If it's worth doing, it's worth doing right.
Published on: December 23, 2014
Last modified on: December 8, 2021