页面不固定高度垂直居中,很多时候会想到用display:table;content高度可自适应,缺点多一层div标签,(ie7以下包括ie7出错)demo如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>水平垂直居中</title>
<style type="text/css">
.out{
display: table;
background: #0f4b89;
width: 500px;
height: 500px;
}
.inner{
display: table-cell;
vertical-align: middle;
}
.content{
margin: 0 auto;
width: 80%;
background: #fff;
word-break: break-all;
}
</style>
</head>
<body>
<!-- <a href="http://127.0.0.1/learning/demo/referrer/b.html">跳转到b.html</a> -->
<div class="out">
<div class="inner">
<div class="content">
能接受的精神病的精神病的加班时间的保时捷的不仅是把的计算机fbghfbhgfbghbfhgbhfbghfbfgbfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
</div>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>wap不固定高度垂直居中</title>
<style type="text/css">
.out{
position: relative;
background: #0f4b89;
width: 100%;
height: 400px;
}
.content{
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate3d(-50%,-50%,0);
width: 80%;
background: #fff;
word-break: break-all;
}
</style>
</head>
<body>
<!-- <a href="http://127.0.0.1/learning/demo/referrer/b.html">跳转到b.html</a> -->
<div class="out">
<div class="content">
能接受的精神病的精神病的加班时间的保时捷的不仅是把的计算机fbghfbhgfbghbfhgbhfbghfbfgbfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
</div>
</div>
</body>
</html>
方法三:css总是有很多奇妙的技巧,这种方法来处理不固定高度和宽度的图片水平垂直居中再合适不过(这个方法要保证图片的宽高小于包含它的box)。这种方法也可以实现固定宽高的元素水平垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0" name="viewport" />
<title>prototype原型</title>
<script type="text/javascript" src="js/jquery.js"></script>
<style type="text/css">
html,body{
margin: 0;
padding: 0;
}
.box{
position: relative;
width: 300px;
height: 300px;
background: red;
margin-bottom: 30px;
}
img{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100px;
}
.box-inner{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100px;
height: 100px;
background: blue;
color: #ffffff;
}
</style>
</head>
<body>
<div class="box">
<img src="images/demo.jpg" />
</div>
<div class="box">
<div class="box-inner">我会水平垂直居中</div>
</div>
</body>
</html>