css实现盒子水平垂直居中--3种常用方法
时间:2021-06-10 15:18:09
收藏:0
阅读:16
需要居中显示的子盒子
<body>
<div class="box">我要居中显示</div>
</body>
一、子盒子拥有固定的长宽
1、绝对定位 + margin负间距
.box { background: red; width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; }
2、绝对定位 + margin:auto
.box { background: red; width: 200px; height: 200px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }

二、子盒子没有固定的长宽
绝对定位 + transform:translate(x,y)
.box { background: red; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

三、flex布局
父盒子定义flex布局,项目在主轴和交叉轴的对齐方式全部为 center
<div class="fa">
<div class="box">我要居中显示</div>
</div>
子盒子长宽可固定可不固定
.fa{ height: 300px; display: flex; justify-content: center; align-items: center; margin: 0; padding: 0; } .box { background: red; width: 200px; height: 200px; }
原文:https://www.cnblogs.com/ymbcc/p/14871037.html
评论(0)