不定宽高的怎么实现垂直居中:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>haorooms不固定高度div写法</title>
<style>
.center {
position: fixed;
top: 50%;
left: 50%;
background-color: #000;
width:50%;
height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
css3实现方式:
只要三句话就可以实现不定宽高水平垂直居中。
justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;
margin实现:
margin的值设置为auto,可以让我们对剩余空间进行分配!我们知道,块级元素设置为margin:0 auto;可以左右居中显示!那有没有办法让margin设置为margin:auto之后,上下左右都居中呢?上下左右都居中,就可以实现我们的垂直居中了!
答案是有的,只要我们让上下有足够的空间,就可以让margin的auto来分配上下空间。
我们可以利用定位的方式,让margin上下左右都有足够的空间!那么就可以用margin:auto来实现垂直居中了!
实现html如下:(做一个简单的垂直弹框)
<div class="father">
<div class="son"></div>
</div>
css代码如下,很简单,兼容性也蛮好,支持IE8+
.father{position:fixed;width:100%;height:100%;top;0;left:0;background-color:rgba(0,0,0,.7);}
.son{position: absolute;top:0;left:0;bottom:0;right:0;width:50%;height:50%;margin:auto;background-color:red;}
这样就可以实现垂直居中了,是不是很简单?!!