Centering a div inside another div

Centering text inside a div is easy. But how can we center a div inside another div, both horizontally and vertically?

Let’s have a look at a simple markup with three div boxes inside a container div:

HTML: 

<div id="container">
	<div class="box"></div>
	<div class="box"></div>
	<div class="box"></div>
</div>

 

Now, for centering the boxes, we must set them to display: inline-block and its parent div (#container) to text-align: center. By this way, we achieve both a horizontal as well as vertical centering.

CSS:

#container {
    width: 100%;
    text-align:center;
    border: 1px solid grey;
}
 
.box {
    display: inline-block;
    width: 250px;
    height: 250px;
    margin: 10px;
    background: lightblue;
}

 

Demo:

Leave a Reply

Your email address will not be published. Required fields are marked *