Flexbox: center horizontally and vertically

I think you want something like the following.

html, body {
    height: 100%;
}
body {
    margin: 0;
}
.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.row {
    width: auto;
    border: 1px solid blue;
}
.flex-item {
    background-color: tomato;
    padding: 5px;
    width: 20px;
    height: 20px;
    margin: 10px;
    line-height: 20px;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}
<div class="flex-container">
    <div class="row"> 
        <div class="flex-item">1</div>
        <div class="flex-item">2</div>
        <div class="flex-item">3</div>
        <div class="flex-item">4</div>
    </div>
</div>

See demo at: http://jsfiddle.net/audetwebdesign/tFscL/

Your .flex-item elements should be block level (div instead of span) if you want the height and top/bottom padding to work properly.

Also, on .row, set the width to auto instead of 100%.

Your .flex-container properties are fine.

If you want the .row to be centered vertically in the view port, assign 100% height to html and body, and also zero out the body margins.

Note that .flex-container needs a height to see the vertical alignment effect, otherwise, the container computes the minimum height needed to enclose the content, which is less than the view port height in this example.

Footnote:
The flex-flow, flex-direction, flex-wrap properties could have made this design easier to implement. I think that the .row container is not needed unless you want to add some styling around the elements (background image, borders and so on).

A useful resource is: http://demo.agektmr.com/flexbox/

Leave a Comment