CSS

How to vertically (and horizontally) center a div within a div?

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.

Example:

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.

Want to horizontally center like this?

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?

Shares