How do you easily horizontally center a <div> using CSS? [duplicate]
Solution 1:
In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).
#wrapper {
background-color: green; /* for visualization purposes */
text-align: center;
}
#yourdiv {
background-color: red; /* for visualization purposes */
display: inline-block;
}
<div id="wrapper">
<div id="yourdiv">Your text</div>
</div>
Keep in mind that the width of #yourdiv
is dynamic -> it will grow and shrink to accommodate the text inside it.
You can check browser compatibility on Caniuse
Solution 2:
In most browsers this will work:
div.centre {
width: 200px;
display: block;
background-color: #eee;
margin-left: auto;
margin-right: auto;
}
<div class="centre">Some Text</div>
In IE6 you will need to add another outer div
:
div.layout {
text-align: center;
}
div.centre {
text-align: left;
width: 200px;
background-color: #eee;
display: block;
margin-left: auto;
margin-right: auto;
}
<div class="layout">
<div class="centre">Some Text</div>
</div>