实现盒子垂直水平居中
若要仅实现垂直居中,将有关水平居中的设置去掉即可(仅实现水平居中同理)
要先清除边距
盒子如下:
<div class="box">
<div class="inner"></div>
</div>
- 方法一:利用 定位+transform
先给子盒子绝对定位(不要忘记父盒子要相对定位),然后top、left分别设置为50%,再让盒子向上和向左走自己高、宽的一半
.box {
position: relative;
width: 500px;
height: 500px;
background-color: palegreen;
}
.inner {
position: absolute;
width: 200px;
height: 200px;
background-color: rgb(201, 53, 188);
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- 方法二:利用 定位+magin
先给子盒子绝对定位(不要忘记父盒子要相对定位),然后top、left分别设置为50%,再让盒子的margin-top
margin-left
为自己高、宽一半的负值。
.box {
position: relative;
width: 500px;
height: 500px;
background-color: palegreen;
}
.inner {
position: absolute;
width: 200px;
height: 200px;
background-color: rgb(201, 53, 188);
left: 50%;
top: 50%;
margin-top: -100px;(自己高度的一半)
margin-left: -100px;(自己宽度的一半)
}
- 方法三:利用 flex 弹性布局
给父盒子设置弹性盒子属性,然后设置主轴(默认x轴)和侧轴(默认y轴)都为center(如果仅设置主轴,则为水平居中,仅设置侧轴就是垂直居中)
.box {
display: flex;
width: 800px;
height: 400px;
background-color: pink;
/这里不设置flex-direction 即默认主轴为x轴/
justify-content: center; /设置主轴居中对齐/
align-items: center;/设置侧轴居中对齐/
}
.inner {
width: 150px;
height: 100px;
background-color: purple;
color: #fff;
margin: 10px;
}
实现水平居中:
margin:0 auto;
实现垂直居中:
方法一:
给要居中的元素设置display: inline-block;
vertical-align: middle;
要设置一个辅助盒子
<style>
/* 元素垂直居中 */
/* .box {
width: 400px;
height: 400px;
background-color: palegreen;
}
.inner {
width: 100px;
height: 100px;
display: inline-block;
vertical-align: middle;
background-color: pink;
}
.help {
width: 0;
height: 100%;
display: inline-block;
vertical-align: middle;
} */
方法二:
父元素设置diaplay:flex;
子元素设置align-self: center;
.box {
width: 400px;
height: 400px;
background-color: palegreen;
display: flex;
}
.inner {
width: 50%;
height: 50%;
background-color: pink;
align-self: center;
}
方法三
为父元素添加伪元素:before,使得子元素实现垂直居中。
.box {
width: 400px;
height: 400px;
background-color: palegreen;
}
.box::before {
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
.inner {
width: 100px;
height: 100px;
display: inline-block;
vertical-align: middle;
background-color: pink;
} */
<body>
<div class="box">
<div class="inner"></div>
<div class="help"></div>
</div>