I’ve finally found a way to horizontally and vertically center a dynamically sized div element using the CSS3 flexbox layout mode. Still getting the hang of it but I’ll be using these snippets below for an app that I’m working on.

Hopefully flexbox sticks around and solves us of our many web design layout woes. Browser compatibility is still rough but I feel like it’s getting there and we are at a good time now to begin experimenting with it in our apps. You’ll find below that I’ve also added some JavaScript so that you can see that dynamically adding elements still keeps everything centered horizontally and vertically.

NOTE: The below code is only tested on the latest versions of Firefox and Chrome.


html, body {
    height: 100%;
    margin: 0;
body {
    display: flex;
    justify-content: center;
    align-items: center;


<div id="parent">
    <div class="child">This is centered horizontally and vertically!</div>

JavaScript (for dynamically adding elements to parent container):

// using jQuery
$(function () {
    $('#parent').click(function () {

You can also view this in action here: https://jsfiddle.net/6ZTRZ/3/