让div到页面中心

时间:2013-08-18 00:53:37

标签: css css3 html

无论用户是否调整网页大小,我都需要div始终位于页面中心。

我尝试过使用:     保证金:自动;     保证金:0自动;     margin-left:auto; margin-right auto;

但这三个都没有奏效。

HTML:

<div id="grayinnerbackground">
</div>

CSS:

div#grayinnerbackground {
            margin: auto;
            width:1000px;
            background-color: #D9D9D9;
            height: 100%;
            position: fixed;
            z-index: -1;
}

这是一个关于我所谈论的例子的小提琴。 http://jsfiddle.net/ymvDJ/

感谢。

6 个答案:

答案 0 :(得分:1)

如果你想要修复这个位置,请添加这些规则并删除通常的边距技巧:

left: 50%;
margin-left: -25px; // half the width of your element

请在此处查看:http://jsfiddle.net/8DfnG/2/

答案 1 :(得分:0)

删除position: fixed,将width更改为50px并确保0之前的auto margin: auto。{/ p} >

<强>更新

要让div与窗口一样高,请务必将bodyhtml设置为height: 100%;

body, html {
  height: 100%:
}

Updated jsfiddle again

答案 2 :(得分:0)

这个HTML:

<div id="grayinnerbackground">
    foo
</div>

CSS:

div#grayinnerbackground {
            margin: auto;
            width: 50px;
            background-color: #ccc;
            height: 100%;
}

我不完全确定为什么它不起作用,直到我把文字放入div,现在检查一下。

<强>更新

叹气,好吧,我累了。如果div为空,并且您的高度为100%,则它将是其父级的高度的100%,在这种情况下为<body>。由于没有其他内容,<body>的高度为0.给<div>一个绝对高度,它会弹出:

div#grayinnerbackground {
            margin: auto;
            width: 50px;
            background-color: #ccc;
            height: 10px;
}

答案 3 :(得分:0)

您可以使用

position: fixed;
left: 50%;
width: 50px;
margin-left: -25px; /* width ÷ 2 */

演示http://jsfiddle.net/ymvDJ/3/

答案 4 :(得分:0)

使用:

position: relative 

如果仍然无效,您可能还需要添加它:

display: block;

“position:fixed”表示无论它停留在x和y坐标处。

答案 5 :(得分:0)

你可以试试这个

div#grayinnerbackground {
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    width: 50px;
    background-color: #D9D9D9;
    height: 100%;
}

http://jsfiddle.net/g49Mb/

有关在此工作的更多信息:http://codepen.io/shshaw/full/gEiDt

相关问题