angelo
angelo

Reputation: 1

How do you center divs using only CSS

I currently use this way to center divs using a table and CSS:

<table width="69" border="0" align="center">
  <tr>
    <td width="59">
      <div style="position:relative;">
        <div style="position:absolute; text-align:left; top: 100px;">div2 content goes here</div>
        <div style="position:absolute;text-align:left;">div content goes here</div>
      </div>
    </td>
  </tr>
</table>

Here's the sample: http://2slick.com/div_center.html

Notice how expanding the browser doesn't change the centering of the divs. Does anyone know a way to do something similar using CSS and less code?

Upvotes: 0

Views: 123

Answers (6)

Brendan
Brendan

Reputation: 1883

Here goes...

CSS:

body {
    text-align: center;
    }
div {
    width: 59px;
    margin: auto;
    text-align: left;
    }

HTML:

<div>I'm a div!</div>
<div>So am I!</div>

Upvotes: 0

Jimmy
Jimmy

Reputation: 637

Just set auto margins. See this page: http://www.bluerobot.com/web/css/center1.html

Upvotes: 0

Andrew M
Andrew M

Reputation: 9459

margin:auto

Should do the trick on the centered div. To recreate your example pretty closely:

<div style="width:100px; margin:auto">
    <div style="width:100px;">div content goes here</div>
    <div style="width:100px;">div2 content goes here</div>
</div>

You can then add padding, text alignment etc as needed. Also good to get the inline styles out, but for examples inline is convenient.

Upvotes: 0

wajiw
wajiw

Reputation: 12269

Using a table isn't the best idea when trying to do positioning, unless you're displaying data. If you're trying to use a center layout page design check this out: http://simplebits.com/notebook/2004/09/08/centering/

Upvotes: 0

Mikhail
Mikhail

Reputation: 9007

Common method is without using a table, set div margin:0 auto in its style.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245429

Give the div a fixed width and set both left and right margins to auto.

.centeredDiv {
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}

Upvotes: 2

Related Questions