-1

Possible Duplicate:
How to center DIV in DIV?

Sounds simple but couldn't figure it out:

How do I center a fixed width div on a page?

By default, it goes to the left.

halign is deprecated but I can find a could replacement.

[update]

width:800px;left-margin:auto;right-margin:auto:  

works great.

Is there a way to do this without setting a fixed width?

Community
  • 1
  • 1
user380719
  • 9,663
  • 15
  • 54
  • 89

9 Answers9

2

Try this:

<style>
.centered {
margin-left:auto;
margin-right:auto;
}
</style>

<div class="centered">
Some text
</div>
Olli
  • 752
  • 6
  • 20
1
<div style="margin:0 auto">content here</div>
epignosisx
  • 6,152
  • 2
  • 30
  • 31
1

A div, by default, is the entire width of the page. You can center the contents by setting the css of the div to:

.mydiv
{
    text-align: center;
}

OR

You can center the div itself by doing this:

.mydiv
{
    display: inline-block; /* make it be only as wide as its contents */
    margin: auto; /* centering magic by making the margins equal and maximum */
}
evan
  • 12,307
  • 7
  • 37
  • 51
1

You can center any div that doesn't span the entire page. Say your div is

.div {
width: 80%;
margin: 0 auto;
}

Then it will work fine. As Evan said "display: inline-block;" will make the div as wide as its contents which will also work great with "margin: 0 auto;".

Anirath
  • 55
  • 1
  • 9
0
div {
  margin-left: auto;
  margin-right: auto;
}
Alfred Fazio
  • 956
  • 7
  • 10
0

margin:auto; should do the trick, I guess?

Sparky
  • 98,165
  • 25
  • 199
  • 285
0

As long as you have an appropriate doctype declared, centering a div on a page should be as easy as:

#someDiv {
    width: 624px;
    margin-left: auto;
    margin-right: auto;
}

If you're using IE and you don't have a doctype declared (you're running in quirks mode), this won't work. The fix is to add the appropriate doctype declaration to your page. You can find the appropriate declaration here:

W3C QA - Recommended list of Doctype declarations you can use in your Web document

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
0

There's generally two ways of doing (that I've seen). One with the margin attribute and another with positioning and left:50%

http://jsfiddle.net/NvaEE/

<br>
<div class="first"> I have a fixe dwidth</div>
<br>
<div class="second"> I have a fixe dwidth</div>

div{width:200px; background:#ddd;}

div.first{margin:0 auto;}
div.second{position:absolute;left:50%;margin-left:-100px}
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
0

You wrap it in a container div that spans the width of the page and give that container div the

text-align: center;

css attribute.

There are other methods, such as managing the margins and widths. For most cases, you can get by with text-align.

Bob
  • 41
  • 2