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?
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.
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.
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.
INSIDE a div or other block element. If you need to center a div itself, then you need to use "margin: 0 auto".
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With