Div水平居中,垂直居中 [英] Div horizontally center and vertically middle

查看:198
本文介绍了Div水平居中,垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将页面的正文的div水平中心和垂直中间对齐。

I want to align a div horizontally center and vertically middle of the body of a page.

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;
}

我有这个html:

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

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

现在它的行为正如我想要的那样,但如果我调整浏览器的大小, ,也许这是因为绝对的定位。我显示一些屏幕截图:
在调整大小firefox:

Now it is behaving as I want it to, but if I resize the browser, it became completely distorted, perhaps this is because the absolute positioning. I am showing some of the screenshots: in resized firefox:

在调整大小的chrome中:

in resized chrome:

in resized ie:

in resized ie:

在最大化的窗口中是:

in maximized window it is:

有没有办法解决这个问题,并使用相对定位实现这个居中对齐?

Is there any way to solve this problem and achieve this centered alignment using relative positioning?

感谢。

编辑:

在firefox中,调整大小时不显示滚动条,但它出现在其他浏览器中。

In firefox no scrollbar appears while resizing but it appears in other browsers.

推荐答案

尝试:

.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*/
}

您将它移动到中心,向左和向上移动一半的尺寸 - 即使在调整大小

You move it to the center, and than back left and up by half the dimensions - that will center it even on resize

这篇关于Div水平居中,垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆