flex方式 <div class="dv"> <div class="dv2"></div> </div> .dv{ width: 400px; height: 400px; background-color: red; display: flex; justify-content: center; align-items: center; } .dv2{ width: 200px; height: 200px; background-color:blue; }
position方式
<div class="dv3"> <div class="dv4"> </div> </div> <style> .dv3 { width: 400px; height: 400px; background-color: yellow; position: relative; } .dv4 { width: 200px; height: 200px; position: absolute; background-color: purple; margin: auto; top: 0; bottom: 0; left: 0; right: 0; } </style>
position+transform 方式
<div class="dv5"> <div class="dv6"> </div> </div> <style> .dv5 { width: 400px; height: 400px; background-color: green; position: relative; } .dv6 { width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; background-color: white; transform: translate(-50%, -50%); } </style>
来源:https://www.cnblogs.com/lj-960427/p/12442058.html