How to make a div center align in HTML

Possible Duplicate:
How to center a div in a div?

One simple way to make an object centered in HTML is using align='center' , but it's not working for a div.

I tried:

style='text-align:center';
style='left:50%';

I even true a center tag

<center>

But I can't make my target div to be center.


<!DOCTYPE html>
<html>
  <head>
    <title>Center</title>
  </head>
  <body>

    <div style="text-align: center;">
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>
    </div>

  </body>
</html>

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.


it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/; width: 50%; height: 300px; left: 50%; top:100px; margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/; width: 50%; height: 300px; margin: 0 auto">blblablbalba</div>

for both techniques it is imperative to set de width

链接地址: http://www.djcxy.com/p/13200.html

上一篇: jQuery同位素居中

下一篇: 如何在HTML中对齐div中心