Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you easily horizontally center a <div> using CSS? [duplicate]

Tags:

html

css

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 
like image 666
cmcginty Avatar asked Mar 06 '09 08:03

cmcginty


People also ask

How do I center a div horizontally in CSS?

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.

How can I center a div within another div duplicate?

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.

How do I center absolutely horizontally in CSS?

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).


2 Answers

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

like image 69
Tivie Avatar answered Sep 24 '22 00:09

Tivie


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>
like image 39
Antony Scott Avatar answered Sep 26 '22 00:09

Antony Scott