开发者

Align container vertically

开发者 https://www.devze.com 2023-03-10 00:41 出处:网络
I would like to align my container div to center vertically just like it is aligning himself horizontally because of margin: auto;. I\'ve searched some time on google on how to do that but it does not

I would like to align my container div to center vertically just like it is aligning himself horizontally because of margin: auto;. I've searched some time on google on how to do that but it does not seem to be working for me. Maybe there is some kind of universal way to do that, as easy as margin: auto; method for horizontal centering? Because it seems for me very strange that we live in 2011 year and there is still no simple css command for do开发者_如何学运维ing this task...

#container
{
    margin: auto;
    width: 960px;
    height: 640px;
    background-color: brown;
}

Align container vertically


There are tons of tutorials for vertical alignment, especially for IE, which needs special care. One of them: Vertically center content with CSS. Also another answer here.


Can it be even simpler...

html, body {
    overflow:hidden
}
#container {
    width:960px;
    height:640px;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-320px;
    margin-left:-480px;
    background:brown
}

The overflow:hidden is to hide the scrollbar that appears (html for IE6 and body for IE5). I don't know why this happens.

But if you want to keep it scrollable if the browser window is smaller, just make the height 639px and remove the overflow:hidden.


If your div has a fixed height, you can align it vertically by adding another div (with a float) with a negative margin (half the height of the main div) and then alter your div's CSS (adding the clear).

Also don't forget to specify the 100% height of the html and body, without that it doesn't work.

Like this:

CSS:

html {
    overflow: auto;
}
html, body {
    margin:0;
    padding:0;
    height:100%;
}
#alignDiv {
    float:left;
    height:50%;
    margin-bottom:-320px; /* half the centered div */
    width:1px;
}
#container
{
    margin: 0 auto;
    width: 960px;
    height: 640px;
    background-color: brown;
    clear:left; /* without the clear it won't center */
}

html:

<div id="alignDiv"></div>
<div id="container"></div>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号