Create a Horizontally Center div inside another div

If you have got stuck while trying to create a horizontally center div inside another div, then the following CSS code can be a quick and easy help.

Now suppose you have a HTML document with two div elements as following:

<div id=”outer-div”>
<div id=”inner-div”> Here is your text</div>
</div>

Now if you run this code, you will get an output similar to the following:

Initial_display

But your aim is to make the inner div centralized.

Now there are 2 ways of doing it.

  1. Using both the div Ids.

Therefore, we can add some simple CSS code and get out desired result. We are going to use the two div ids for this.

For the outer div id:

#outer-div{
width:100%;
text-align: center;
}

For the inner div id:
#inner-div{
display:inline-block;
}

Below you can find the complete HTML document code for the above solution:

<!DOCTYPE html>
<html>
<style>
body {
background:#ebebeb;
margin:10px;
font-size:100%;
}
div {
background:#ffffff;
border: 5px solid;
text-align: left;
border-color:#fff777;
}
#outer-div{
width:100%;
text-align: center;
}
#inner-div{
display:inline-block;
}
</style>
<body>
<div>
<div>
<strong>First Set:</strong><br/>
This is result of the following code snippet:<br/>
&lt;div&gt;<br/>
&lt;div&gt;First Set&lt;/div&gt;<br/>
&lt;/div&gt;<br/>
</div>
</div>
<br/><br/>
<div id="outer-div">
<div id="inner-div">
<strong>Second Set</strong><br/>
This the result of the following code snippets:<br/>
CSS:<br/>
#inner-div{<br/>
display:inline-block;<br/>
}<br/>
#outer-div{<br/>
width:100%;<br/>
text-align: center;<br/>
}<br/>
HTML<br/>
&lt;div id="outer-div" &gt;<br/>
&lt;div id="inner-div" &gt;<br/>
</div>
</div>
</main>
</body>
</html>

The above code will look something like this in the browser:

Using_both_inner_and_outer_divs

  1. Using the inner div Id and a fixed inner div width:

<!DOCTYPE html>
<html>
<style>
body {
background:#ebebeb;
margin:10px;
font-size:100%;
}
div {
background:#ffffff;
border: 5px solid;
text-align: left;
border-color:#fff777;
}
#inner-div{
width: 70%;
margin: 0 auto;
}
</style>
<body>
<div>
<div>
<strong>First Set:</strong><br/>
This is result of the following code snippet:<br/>
&lt;div&gt;<br/>
&lt;div&gt;First Set&lt;/div&gt;<br/>
&lt;/div&gt;<br/>
</div>
</div>
<br/><br/>
<div id="outer-div">
<div id="inner-div">
<strong>Second Set</strong><br/>
This the result of the following code snippets:<br/>
CSS:<br/>
#inner-div{<br/>
width: 70%; <br/>
margin: auto;<br/>
}<br/>
HTML<br/>
&lt;div id="outer-div" &gt;<br/>
&lt;div id="inner-div" &gt;Second Set&lt;/div&gt; <br/>
&lt;/div&gt;
</div>
</div>
</body>
</html>

The above code will look something like this in the browser:

Using_only_inner_div

You can use any of the above options and get the div horizontal center-aligned.