①內邊距;
②外邊距;
③小盒子轉換成行內塊元素再結合vertical-align;
④絕對定位;
⑤絕對定位結合margin(定位方位的一半加上margin自身寬高的一半);
⑥絕對定位結合margin(四個方位都設為0,然后將margin設為auto自適應)。
⑦使用定位結合transform屬性和translate()屬性值,定位讓小盒子left:50%,top:50%,然后配合transform:translate(-50%,-50%):(便是移動小盒子自身寬度的百分之五十)即可。優點是無論盒子多高多寬,大盒子多好多寬,都能讓小盒子在大盒子中做水平垂直居中
方法一
*{margin: 0;padding: 0;} 方法一、純margin .boss{ width: 500px; height: 500px; background: orange; overflow: hidden; } .box{ width: 200px; height: 200px; background: green; margin-left: 150px; margin-top: 150px; } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法二
方法二、純padding .boss{ width: 350px; height: 350px; background: orange; padding-left: 150px; padding-top: 150px; } .box{ width: 200px; height: 200px; background: green; } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法三
方法三、display:inline-block;text-align:center;line-height .boss{ width: 500px; height: 500px; background: orange; text-align: center; line-height: 500px; } .box{ width: 200px; height: 200px; background: green; display: inline-block; vertical-align: middle; } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法四
方法四、純定位 .boss{ width: 500px; height: 500px; background: orange; position: relative; } .box{ width: 200px; height: 200px; background: green; position: absolute; left: 150px; top: 150px; } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法五
方法五、定位 + margin 可以取負值*/ .boss{ width: 500px; height: 500px; background: orange; position: relative; } .box{ width: 200px; height: 200px; background: green; position: absolute; left: 50%; 移動父元素寬度的一半 margin-left: -100px; 讓自身讓左邊移動自身寬度的一半 top: 50%; 移動父元素高度的一半 margin-top: -100px;讓自身讓上邊移動自身高度的一半 } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法六
方法六、定位 + margin:auto; .boss{ width: 500px; height: 500px; background: orange; position: relative; } .box{ width: 200px; height: 200px; background: green; position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } <body> <!-- 一個寬高為200*200的小盒子在一個寬高為500*500的大盒子里面做水平垂直居中效果,請問你能用幾種方法實現?(6種) --> <div class="boss"> <div class="box"></div> </div> </body>
方法七
<style type="text/css"> *{ margin: 0; padding: 0; } .boss{ width: 500px; height: 500px; background: orange; position: relative; } .box{ width: 200px; height: 200px; background: green; position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="boss"> <div class="box"></div> </div> </body>