第一种, 针对内联元素居中.
<div class="box box1"> <span class="test">垂直居中</span> </div> <style> .box{ width: 200px; height: 200px; border:1px solid red; } .box1{ display: table-cell; vertical-align: middle; text-align: center; } .test{ width: 30px; height: 30px; border:1px solid black; } </style>
2: 弹性盒子
<div class="box box1"> <div class="test"></div> </div> <style> .box{ display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; border:1px solid red; } .test{ width: 30px; height: 30px; border:1px solid black; } </style>
3translate
<div class="box box1"> <div class="test"></div> </div> <style> .box{ position: relative; width: 200px; height: 200px; border:1px solid red; } .test{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); width: 30px; height: 30px; border:1px solid black; } </style>