8

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

omkar
  • 216
  • 2
  • 10

4 Answers4

7

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, e.g., 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, i.e., 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.
Brigand
  • 84,529
  • 20
  • 165
  • 173
6

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>
kba
  • 19,333
  • 5
  • 62
  • 89
0

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/

Jasper
  • 75,717
  • 14
  • 151
  • 146
-5
<center><div></div></center>

try that

  • 3
    The OP says HTML5. The `
    ` element is not allowed in HTML5, which is why you're getting down votes.
    – Brigand Dec 21 '11 at 00:39
  • 2
    `This tag has been deprecated in HTML 4`. *Source: https://developer.mozilla.org/en/HTML/Element/center* – Jasper Dec 21 '11 at 00:41