(1)宽度和高度已知的
.box { width: 400px; height: 200px; position: relative; background: red; } .content { width: 200px; height: 100px; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -50px; background: green; } </style> <div class="box"> <div class="content"></div> </div>
(2)宽度和高度未知
<style> .box { width: 400px; height: 200px; position: relative; background: red; } .content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: green; } </style> <div class="box"> <div class="content"></div> </div>
(3)flex布局
<style> .box { width: 400px; height: 200px; background: red; display: flex; justify-content: center; align-items: center; } .content { width: 200px; height: 100px; background: green; } </style> <div class="box"> <div class="content"></div> </div>
原文地址:https://www.cnblogs.com/hongchenzimo/p/11080770.html
时间: 2024-10-10 16:53:32