CSS水平垂直居中的方法
水平居中:
1.直接加margin:auto
2.使用flex布局
<body> <div class="box1"></div> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } body { display: flex; justify-content: center; } .box1 { width: 200px; height: 200px; background-color: red; } </style> <script> </script> </body>
垂直居中
1.使用flex布局
<style> // body属于html,div组件属于body,所以要先把html和body撑满 html,body { width: 100%; height: 100%; margin: 0; padding: 0; } body { display: flex; align-items: center; justify-content: center; } .demo1 { width: 300px; height: 300px; background-color: orange; } </style>
2.使用绝对定位
<body> <div class="box1"> <div class="box2"></div> </div> <div class="box3"></div> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } body { width: 5000px; } .box1 { width: 300px; height: 300px; background-color: orange; /* 这里只要position不为static,即开启position就行,只不过会根据不同的值而变换效果 */ position: fixed; } .box2 { width: 200px; height: 200px; background-color: red; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } .box3 { width: 400px; height: 400px; background-color: blue; } </style> <script> </script> </body>
3.绝对定位+transform: translate(-50%,-50%);
<body> <div class="box1"> <div class="box2"></div> </div> <div class="box3"></div> <style> html,body { width: 100%; height: 100%; margin: 0; padding: 0; } body { width: 5000px; } .box1 { width: 300px; height: 300px; background-color: orange; position: fixed; } .box2 { width: 200px; height: 200px; background-color: red; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } </style> <script> </script> </body>
4.使用table-cell搭配vertical-align
<div id="box"> <div id="content">bcebcuebcuewbciuebcuecbue</div> </div> #box { display: table-cell; width: 200px; height: 200px; vertical-align: middle; background-color: orange; } #content { background-color: skyblue; }