css - 为什么这里的margin-top为-12.5%时div才垂直居中?

查看:127
本文介绍了css - 为什么这里的margin-top为-12.5%时div才垂直居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

代码如下

<!DOCTYPE html>
<html>
<head>
<title> 多行文字实现垂直居中 </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
html,body{
height:100%;
}
div#wrap{
position:absolute;
top:50%;
left:50%;
margin-left:-25%;
margin-top:-12.5%;
display:table;
background-color:gray;
width:50%;
height:50%;
_position:relative;
overflow:hidden;

}
div#subwrap {
vertical-align:middle;
display:table-cell;
text-align:center;
_position:absolute;
_top:50%;
_left:50%;
}
div#content { 
_position:relative;
_top:-50%;
_left:-50%;
}
</style>
</head>
<body>
<div id="wrap">
    <div id="subwrap">
        <div id="content">
  现在我们要使这段文字垂直居中显示!
  <pre>
  div {
  padding:25px;
  border:1px solid #FF0099;
  background-color:#FFCCFF;
 }
 </pre>
        </div>
    </div>
</div>
</body>
</html>

这是使内部div居中的同时,外部div也相对于页面居中。外部div设置居中时topleft都移动了50%,所以为了让其居中,margin-topmargin-left我本来都设置为-25%margin-left:-25%;确实让水平居中了,但垂直的话只有让margin-top的值为-12.5%,这是为什么。求告知。

解决方案

因为margin-top设置百分比时的计算参考对象是父元素的宽度,而你说的12.5%也不是正好居中,只是因为1920接近1080的两倍而产生的错觉。
你要居中可以用left:25%和top:25%而不用margin

这篇关于css - 为什么这里的margin-top为-12.5%时div才垂直居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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