1.固定高宽(width: 200px;height: 100px;)
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
margin-left: -100px;
margin-top: -50px;
background: red;
2.不固定高宽div垂直居中的方法(利用伪元素)
index.html
<div class="block" style="height: 300px;">
<div class="centered">
<h1>居中标题</h1>
<p>abc</p>
</div>
</div>
index.css
/* This parent can be any width and height */
.block {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 50%;
}
3.这种方法是比较成熟的不是固定高宽div的垂直居中的方法
<div class="center"></div>
.center {
position: fixed;
top: 50%;
left: 50%;
background-color: #000;
width:50%;
height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}