How do I center a <div>?

Possible Duplicate:
How to center DIV in DIV?

I want to center a <div> (I'm new to HTML5 and the <center> tag is no more), and by all means avoid using a table. This is what I've got as CSS for the <div> in question so far:

#roundedcorner {
    -moz-border-radius: 15px;
    border-radius: 15px;
    background-image: url(file:///Macintosh%20HD/Users/julesmazur/Desktop/TAN3.0/Photos/bodydivbg.png);
    width: 960px;
    left: 50%;
    font-family: Ubuntu;
}

(for anyone curious, Ubuntu courtesy of Google Web Fonts).


The typical trick is margin: auto . It'll center it inside what-ever it's in.

demo


Besides that I have a few comments on your code (since you're a beginner).

  • left: 50%; does nothing unless you change the position style, eg, position: relative; or position: absolute;
  • The container the div is in needs to be larger than it -- otherwise centering it really doesn't mean anything. This is because styles like margin: auto are relative to the parent container, ie, it needs space.
  • For Google Web Fonts, make sure you have your @font-face with it. Also, use alternatives. Not all browsers support web fonts, and the more control you have: the better. An example would be font-family: Ubuntu, Arial, Sans; , ordered from most preferred to most likely backups.

  • Don't use left . This will create a gab in the page on the left side. Instead, use margin: 0 auto .

    <div style="margin:0 auto;width:960px">I'm centered.</div>
    

    You can center DOM elements that are absolutely positioned (horizontally and vertically) by using:

    div {
        position    : absolute;
        width       : 960px;
        height      : 500px;
        left        : 50%;
        top         : 50%;
        margin-top  : -250px;
        margin-left : -480px;
    }
    

    Here is a demo: http://jsfiddle.net/KBHjT/

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

    上一篇: 我如何居中一个iframe?

    下一篇: 我如何居中<div>?