html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four">dasdasdjka</div>
<div class="five">I am gray</div>
<div class="six"><div class="content"><div><div>
<div class="seven">移动端用的比较多,无需设置宽高</div>
<div class="eight"><div class="content">A</div></div>
</body>
</html>
css:
.one{
position:absolute;
width:200px;
height:200px;
top:50%;
left: 50%;
margin-top:-100px;
margin-left: -100px;
background:red;
}
.two {
position: fixed;
width:180px;
height:180px;
top:50%;
left: 50%;
margin-top:-90px;
margin-left: -90px;
background:orange;
}
.three {
position: fixed;/* absolute也行 */
width: 160px;
height: 160px;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: pink;
}
.four {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 140px;
height: 140px;
background: purple;
}
.five {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
background: gray;
}
.six {
width:90px;
height:90px;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
background:yellow;
color:black;
}
.six .content {
width: 50px;
height: 50px;
background: green;
}
/* 好处是无需设置宽高,移动端用的比较多 */
.seven {
position:absolute;
width: 120px;
height: 120px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: blue;
}
.eight {
position: fixed; /* absolute */
left: 0;
top: 0;
right: 0;
bottom: 0;
text-align: center;
}
.eight:before {
content: '';
display: inline-block;
vertical-align:middle;
height: 100%;
}
.eight .content {
display:inline-block;
vertical-align:middle;
width: 60px;
height: 60px;
line-height:60px;
color:red;
background:yellow;
}
效果图:
作者:徐尤熙
链接:https://www.zhihu.com/question/20543196/answer/89218605
来源:知乎