①内边距;
②外边距;
③小盒子转换成行内块元素再结合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>
