2012-03-11 152 views
11

我想对齐一个页面的水平中心和垂直中间的bodyDiv水平中心和垂直中间

的CSS:

.loginBody { 
    width: 100%; 
    height: 100%; 
    margin: 0; 
    padding: 0; 
    background: #999; /* for non-css3 browsers */ 
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); /* for IE */ 
    background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000)); /* for webkit browsers */ 
    background: -moz-linear-gradient(top, #ccc, #000); /* for firefox 3.6+ */ 
} 
.loginDiv { 
    position: absolute; 
    left: 35%; 
    top: 35%; 
    text-align: center;   
    background-image: url('Images/loginBox.png'); 
    width:546px; 
    height:265px; 
} 

我有这个网站:

<body class="loginBody"> 
    <form id="form1"> 
    <div class="loginDiv"> 

    </div> 
    </form> 
</body> 

现在它表现为我想它,但如果我调整浏览器,它成为完全扭曲,或许这是因为绝对的定位。我显示了一些截图: 在调整火狐: 在调整大小的镀铬enter image description here

enter image description here

在调整即

enter image description here

最大化的窗口,它是: enter image description here

有什么方法可以解决这个问题,并使用相对定位来实现这种居中对齐?

谢谢。


编辑:

在Firefox,而调整没有出现滚动条,但它出现在其他浏览器。 enter image description here

回答

15

试试这个:

.loginDiv { 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    text-align: center;   
    background-image: url('Images/loginBox.png'); 
    width:546px; 
    height:265px; 
    margin-left: -273px; /*half width*/ 
    margin-top: -132px; /*half height*/ 
} 

你一半的尺寸将其移动到中心,不是往后左右了 - 这将居中即使在调整

+0

感谢您的帮助,这是现在的工作,但在Firefox的一个问题日ere在调整大小时没有滚动条,但它存在于其他浏览器中。我更新了我的问题。请看看它。 – 2012-03-11 15:55:20

+0

如果你不想要滚动条 - 只需将“overflow:hidden”添加到主体 – StilgarBF 2012-03-11 16:00:03

+0

不,我想要滚动条,所以我在主体中设置了“overflow:auto”,但仍然没有滚动条。 – 2012-03-11 16:03:54

3
#div { 
    height: 200px; 
    width: 100px; 
    position:absolute; 
    top: 50%; 
    left: 50%; 
    margin-top: -100px; 
    margin-left: -50px; 
} 

这是一个以div为中心的常用方法。你把它放在绝对位置,然后把它移到一半到一半。然后用边距调整位置,使其与定位的div的一半尺寸一致。

仅供参考(本使用固定的定位虽然保持到位股利甚至滚动,帮助时,做模态弹出窗口时.. http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

+0

感谢您的帮助。它现在正在工作,但Firefox中的一个问题是调整大小时没有滚动条,但它存在于其他浏览器中。我更新了我的问题。请看看它。 – 2012-03-11 15:55:58

+0

http://jsfiddle.net/mAVd6/2/这是否基本上反映了您的页面是如何构建的?它在Firefox中产生滚动条吗?其它浏览器? - 如果将绝对值与固定值交换,滚动条会发生什么变化?! – Greg 2012-03-11 16:09:03

+0

如果我将位置更改为绝对位置,那么在任何浏览器中都不会出现滚动条。 – 2012-03-11 16:15:09

4

让一个div是对网页的内容,并作出“内容”类具有以下CSS。这为我工作的jQuery Mobile的使用PhoneGap的Android设备。希望它可以帮助别人。

CSS

.content { 

     width: 100%; 
     height: 100%; 
     top: 25%; 
     left: 25% 
     right: 25%; 
     text-align: center; 
     position: fixed; 
}