Back
How to Center a Div

How to Center a Div Vertically and Horizontally

In this quick tutorial, I am going to show you how to center a div vertically and horizontally inside another div.

I will also show you how to individually centre a div either horizontally or vertically assuming you have a fixed width and flexible height content box.

There are various ways of achieving this but I am going to share a few.

However, please bear in mind that there are some ways that may eventually hunt you in the course of maintaining your code, so be careful of the methods you adopt.

Before we continue, these solutions I am about to show you should work on all major browsers.

Horizontally and Vertically Center Div

The code below will centralize your div both horizontally and vertically, thereby bringing the child div to the middle of the parent div.

Please note: Use your preferred width size.

<html>
<head>
<style>
.outerDiv {
    height: 100%;
    width: 100%;
    display: table;
    position: absolute;    
}
 
.middleDiv {
    height: 100%;
    width: 100%;
    vertical-align: middle;
    display: table-cell;
}
 
.innerDiv {
    margin-left: auto;
    margin-right: auto; 
    width: /*whatever width you want to keep*/;
}
</style>
</head>
<body>
<div class="outerDiv">
    <div class="middleDiv">
        <div class="innerDiv">
            <h1>The heading</h1>
            <p>Some dynamic content placed here...</p>
        </div>
    </div>
</div>
</body>
</html>
 
how to center a div
how to center a div horizontally and vertically

Horizontally Centralize a Div

Using CSS we will centralize the inner div horizontally. Using the code below will only centralize the child div horizontally and without setting vertical alignment. Your div will be automatically aligned to the top.

<html>
<head>
<style>
.outerDiv {
    height: 100%;
    width: 100%;
    display: table;
    position: absolute;    
}
.innerDiv {
    width: /* Specify any width less than or % of containing div */
    margin: 0 auto;
}
 
/* If you are targeting IE8+ then below one is better*/
 
.innerDiv {
    display: table;
    margin: 0 auto;
}
</style>
</head>
<body>
<div class="outerDiv">
    <div class="innerDiv">
	<h4>heading here</h4>
        <p>Content will go here...</p>
    </div>
</div>
</body>
</html>

Vertically Centralize a Div

Using CSS we will centralize the inner div vertically. Use the code below to centralize the child div vertically and without setting horizontal alignment. Your div will automatically align to left.

<html>
<head>
<style>
.outerDiv {
    float:left; 
    height:50%; 
    margin-bottom:-120px;
}
.innerDiv {
    clear:both; 
    height:240px; 
    position:relative;
}
</style>
</head>
<body>
<div class="outerDiv">
    <div class="innerDiv">
	<h4>heading here</h4>
        <p>Content will go here...</p>
    </div>
</div>
</body>
</html>

Leave A Reply

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