葉無聞 2020-03-23
.class { width: 960px; margin: 0 auto; }
父元素需要设置position为非static定位,如果需要左右也居中,加上left: 0;right: 0;
即可。
.vMiddle { width: 100px; height: 100px; position: absolute; top: 0; bottom: 0; margin: auto; }
样例代码
<html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .middle { position: absolute; height: 100px; width: 100px; top: 0; bottom: 0; background-color: black; margin: auto; } </style> </head> <body> <div style="position:relative;width:200px;height:600px;background-color: aliceblue;"> <div class="middle"> </div> </div> </body> </html>