35

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?

Linas
  • 4,380
  • 17
  • 69
  • 117
  • do you mean : http://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen ? – Snake Eyes Nov 22 '11 at 14:38
  • @Michael I don't think he's having trouble with centering (confusing title in this case). If you read the question, he's having trouble with the width of the content. – Josh Darnell Nov 22 '11 at 14:40
  • Are you asking how to horizontally center an element with an unknown width? – thirtydot Nov 22 '11 at 14:41
  • 1
    is the div called #page or #container? – PiTheNumber Nov 22 '11 at 14:42
  • yes i can center it without any problem but for that i need to use width:some with px; and if my content width get bigger or smaller than my container with some page elements gets messed up – Linas Nov 22 '11 at 14:43
  • @SnakeEyes Your link points to how to center a div using jQuery. – TARKUS Jul 05 '16 at 23:43

4 Answers4

57

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;
}
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • I just edited your jsfiddle and removed all styling for `#container` and it still works. I guess the `text-align` on `body` does the trick? Tested in firefox. – Code Poet Nov 15 '13 at 12:50
  • 1
    @CodePoet: Doing that means `#container` is now simply full width and the text inside it is centered. [Which isn't what we're after.](http://jsfiddle.net/thirtydot/rjY7F/420/) – thirtydot Nov 16 '13 at 21:28
16

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.

Nate B
  • 6,338
  • 25
  • 23
6

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; }
Viruzzo
  • 3,025
  • 13
  • 13
1

how about this?

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

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

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180