盒子居中5种方式

1 <div class="box" id="box">
2    垂直居中
3 </div>
/* 公共样式 */
1
html, 2 body { 3 overflow: hidden; 4 height: 100%; 5 } 6 7 .box { 8 line-height: 48px; 9 box-sizing: border-box; 10 width: 100px; 11 height: 50px; 12 border: 1px solid lightblue; 13 text-align: center; 14 } 15 16 17 body { 18 position: relative; 19 }
/* 方式一 */
1
.box { 2 position: absolute; 3 top: 50%; 4 eft: 50%; 5 margin-top: -25px; 6 margin-left: -50px; 7 }
/* 方式二 */
1
.box { 2 position: absolute; 3 top: 50%; 4 left: 50%; 5 transform: translate(-50%, -50%); 6 }
/* 方式三 */
1
.box { 2 position: absolute; 3 left: 0; 4 top: 0; 5 right: 0; 6 bottom: 0; 7 margin: auto; 8 }
/* 方式四 */
1
body{ 2 display: flex; 3 justify-content: center; 4 align-items: center; 5 }
/* 方式五 */
1
let HTML = document.documentElement, 2 winW=HTML.clientWidth, 3 winH=HTML.clientHeight, 4 boxW=box.offsetWidth, 5 boxH=box.offsetHeight; 6 box.style.position="absolute" 7 box.style.left=(winW-boxW)/2+'px' 8 box.style.top=(winH-boxH)/2+'px'
posted @ 2020-07-08 16:27  爱迪西  阅读(360)  评论(0)    收藏  举报