五种水平垂直居中方式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0"> <title>五种水平垂直居中</title> <!-- IMPORT CSS --> <style> html, body { position: relative; /* height: 100%; */ overflow: hidden; } .box { box-sizing: border-box; width: 100px; height: 50px; line-height: 48px; text-align: center; font-size: 16px; border: 1px solid lightblue; background: lightcyan; } /* 定位1 */ /* body { position: relative; } */ /* 1.通过绝对定位 .box { position: absolute; top: 50%; left: 50%; margin-top: -25px; margin-left: -50px; } */ /* 2.通过绝对定位 .box { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } */ /* 3.通过绝对定位 .box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } */ /*4.通过flex弹性盒子,常用 body { display: flex; justify-content: center; align-items: center; } */ /* ============ */ body { display: table-cell; vertical-align: middle; text-align: center; /* 固定宽高 */ width: 500px; height: 500px; } .box { display: inline-block; } </style> </head> <body> <div class="box" id="box"> 五种水平垂直居中 </div> <!-- IMPORT JS --> <script> /* 5.利用JS let HTML = document.documentElement, winW = HTML.clientWidth, winH = HTML.clientHeight, boxW = box.offsetWidth, boxH = box.offsetHeight; box.style.position = "absolute"; box.style.left = (winW - boxW) / 2 + 'px'; box.style.top = (winH - boxH) / 2 + 'px'; */ </script> </body> </html>
二.使用绝对定位
1.1.必须要指定元素的宽度和高度
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 position: relative; 7 } 8 9 .box2{ 10 width: 100px; 11 height: 100px; 12 background-color: #bfa; 13 14 15 16 /* 通过绝对定位来设置元素的居中 */ 17 position: absolute; 18 19 /* 四个偏移量都设置为0 */ 20 top: 0; 21 left: 0; 22 bottom: 0; 23 right: 0; 24 25 margin: auto; 26 27 }
三.使用表格(display:xxxx)
1.不需要指定元素的宽度高度(inline-block)
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 /* 将父元素转换为单元格 */ 6 display: table-cell; 7 vertical-align: middle; 8 } 9 10 .box2{ 11 width: 100px; 12 height: 100px; 13 background-color: #bfa; 14 }
四。使用变形
1.不需要设置元素的宽度和高度
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 position: relative; 7 } 8 9 .box2{ 10 width: 100px; 11 height: 100px; 12 background-color: #bfa; 13 14 15 left: 50%; 16 top:50%; 17 transform: translateX(-50%) translateY(-50%); 18 19 }
五。使用弹性盒flex
1.不需要设置元素的宽度和高度
2.会使所有的子元素都在父元素中居中
1 .box1{ 2 width: 800px; 3 height: 500px; 4 border: 2px red solid; 5 6 display: flex; 7 8 justify-content: center; 9 align-items: center; 10 11 12 } 13 14 .box2{ 15 width: 100px; 16 height: 100px; 17 background-color: #bfa; 18 }