如何实现垂直水平居中?
第一种 position定位+margin负距离
前提是知道居中元素的宽高,首先给居中元素定位,之后设置margin的负距离为具体宽高的一半便可达到垂直居中效果
.box {
width: 500px;
height: 500px;
background: pink;
position: relative;
border: 10px solid red;
}
.box-child {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
第二种 position定位+margin auto
position定位加margin auto,与第一种方法相似,设置居中元素的top bottom left right为0px,之后加上外边距magin auto即可
.box {
width: 500px;
height: 500px;
background: pink;
position: relative;
border: 10px solid red;
}
.box-child {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
第三种 position+transform
position定位加上transfom 这种方式的特点是可以不用知道居中元素的宽高,给居中元素定位后left和top都设置成50%,之后向反向平移50%即可
.box {
width: 500px;
height: 500px;
background: pink;
position: relative;
border: 10px solid red;
}
.box-child {
background-color: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
第四种flex布局
首先给父元素设置display:flex让其变成弹性盒子,然后利用弹性盒子的jusyify-content和align-items,将两个属性都设置为center即可
注意:不是给子元素设置 是给容器父元素设置
.box {
width: 500px;
height: 500px;
background: pink;
border: 10px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.box-child {
width: 200px;
height: 200px;
background-color: green;
}