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:
But your aim is to make the inner div centralized.
Now there are 2 ways of doing it.
- 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/>
<div><br/>
<div>First Set</div><br/>
</div><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/>
<div id="outer-div" ><br/>
<div id="inner-div" ><br/>
</div>
</div>
</main>
</body>
</html>
The above code will look something like this in the browser:
- 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/>
<div><br/>
<div>First Set</div><br/>
</div><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/>
<div id="outer-div" ><br/>
<div id="inner-div" >Second Set</div> <br/>
</div>
</div>
</div>
</body>
</html>
The above code will look something like this in the browser:
You can use any of the above options and get the div horizontal center-aligned.