I'm trying to horizontally center a <div>
block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div>
element to be inline with rest of my page. I'll try to draw an example:
page text page text page text page text page text page text page text page text ------- | div | ------- page text page text page text page text page text page text page text page text
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
To move the inner div container to the centre of the parent div we have to use the margin property of style attribute. We can adjust the space around any HTML element by this margin property just by providing desired values to it.
If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With