实现一个子盒子在父盒子里面水平居中和垂直居中的方法都有哪些:
准备工作:
首先准备一个父盒子和子盒子
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
然后设置子盒子和父盒子的宽度和高度和背景色
<style>
.outer {
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
width: 200px;
height: 200px;
background-color: purple;
}
</style>
如下所示:
方法一:
运用定位和margin外边距的方法可以把子盒子水平和垂直居中。
.outer {
/*父盒子相对定位*/
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
/*子盒子绝对定位*/
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
background-color: blue;
}
给子盒子设置top:50%;left:50%,此时子盒子的位置如下图所示:
要想 把子盒子水平和垂直居中,只要往上移动子盒子高度的一半,往左移动子盒子宽度的一半即可,注意正负号。
.outer {
/*父盒子相对定位*/
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
/*子盒子绝对定位*/
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
background-color: purple;
/*移动子盒子宽度和高度的一半*/
margin-top: -100px;
margin-left: -100px;
}
如图:
方法二:
运用定位和变形的缩放translate(x,y)方法,小括号里可以写上(-50%, -50%),即translate自身沿着XY轴位移一半即可。
.outer {
/*父盒子相对定位*/
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
/*子盒子绝对定位*/
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
background-color: purple;
/*运用translate的方法,只需要移动50%即可*/
transform: translate(-50%, -50%)
}
如图:
问题:
translate()和margin有什么区别:
1.margin移动盒子会影响其余的盒子,把其他盒子挤走。
2.位移translate移动盒子不会影响其他盒子,不脱标。
方法三:
利用设置top,left,bottom,right为0,再设置marin :auto;
先设置top,left,bottom,right为0,此时代码为:
.outer {
/*父盒子相对定位*/
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
/*子盒子绝对定位*/
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 200px;
height: 200px;
background-color: purple;
}
图像为:
然后在用margin:0;自适应,实现子盒子垂直居中对齐。
.outer {
/*父盒子相对定位*/
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
/*子盒子绝对定位*/
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
/*用margin外边据自动对其的方法实现,子盒子垂直和水平居中*/
margin: auto;
width: 200px;
height: 200px;
background-color: purple;
}
图像如下:
方法四:
我们可以通过flex让一个子盒子水平和垂直居中。
利用flex布局,把主轴和侧轴的对齐方式都设置为center(给父级添加)。
先给主轴设置居中排列:
<style>
.outer {
/* 给父盒子设置flex布局 */
display: flex;
/* 主轴对齐方式center */
justify-content: center;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
width: 200px;
height: 200px;
background-color: purple;
}
</style>
如下图所示:
再给侧轴设置对齐方式center:
<style>
.outer {
/* 给父盒子设置flex布局 */
display: flex;
/* 主轴对齐方式center */
justify-content: center;
/*侧轴对齐方式center*/
align-items: center;
width: 500px;
height: 500px;
background-color: pink;
}
.inner {
width: 200px;
height: 200px;
background-color: purple;
}
</style>
如图所示: