div在父元素内上下左右居中
作者:互联网
(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>
标签:居中,50%,height,content,width,background,div,上下左右,200px 来源: https://www.cnblogs.com/hongchenzimo/p/11080770.html