Linas
Linas

Reputation: 4408

Centering div with unknown width

i have div <div id="container"></div> which contains all page content including header footer etc.

So i would like to center this div to the center of my page, now i have this css:

#page{
position:relative;
margin:auto;
width:1000px;
}

And it works, but my problem is that content in this div keeps changing so the width changes too, it can be 1000px or 10100px so i need something like width:auto;, how can do something like that?

Upvotes: 36

Views: 29635

Answers (4)

thirtydot
thirtydot

Reputation: 228142

See: http://jsfiddle.net/thirtydot/rjY7F/

HTML:

<div id="container">
    i'm as wide as my content
</div>

CSS:

body {
    text-align: center;
}
#container {
    text-align: left;
    border: 1px solid red;
    display: inline-block;
    /* for ie6/7: */
    *display: inline;
    zoom: 1;
}

Upvotes: 58

Viruzzo
Viruzzo

Reputation: 3025

This will give you a dinamically-sized div that stays at the center of the body and is the smallest size needed to fit the content:

body { text-align: center; }
div.container { display: inline-block; text-align: left; }

Upvotes: 6

Nate B
Nate B

Reputation: 6356

One way is to create a wrapper around your #page element, let's call it #wrapper:

#wrapper {
   position: relative;
   left: 50%;
   float: left;
}
#page {
   position: relative;
   left: -50%;
   float: left;
}

This will allow the #page div to remain a variable width.

Upvotes: 16

PiTheNumber
PiTheNumber

Reputation: 23542

how about this?

body {
  text-align: center;
}
#container {
  text-align: left;
}

Assuming <body><div id="container"></div></body>

Upvotes: 1

Related Questions