css實現盒子水平垂直居中--3種常用方法
阿新 • • 發佈:2021-06-10
需要居中顯示的子盒子
<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; }