Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering div with unknown width

Tags:

html

css

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?

like image 494
Linas Avatar asked Nov 22 '11 14:11

Linas


People also ask

How do I center a specific div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I center a div with fixed width?

When centering divs, if your div has a fixed width you can either absolutely position it and set negative margins as shown in this post. Another way to center such a fixed width div horizontally is to set both its left and right margin to auto. The browser then has to set both margins to the same value.

How do I center a div according to my screen size?

Easiest way to center something regardless of page width is margin: auto; in your CSS, with height and width defined. Show activity on this post. This will center your DIV with class center-div horizontally AND vertically. The margin-left must be negative half of what your width is.

How do I center an empty div?

INSIDE a div or other block element. If you need to center a div itself, then you need to use "margin: 0 auto".


2 Answers

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; } 
like image 113
thirtydot Avatar answered Oct 01 '22 13:10

thirtydot


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.

like image 43
Nate B Avatar answered Oct 01 '22 13:10

Nate B