CSS水平垂直居中布局
1.position设为absolute+margin
position取值 | 脱离标准流 | 定位元素 | 绝对定位元素 | 定位参照对象 |
---|---|---|---|---|
static | 否 | 否 | 否 | 没有 |
relative | 否 | 是 | 否 | 元素自己原来的位置 |
absolute | 是 | 是 | 是 | 最近一级拥有定位的祖先元素(如果找不到,就以视口为参照对象) |
fixed | 是 | 是 | 是 | 视口 |
对于绝对定位的元素,会满足以下两个公式:
- 定位参照对象的宽度 = left + right + margin-left + margin-right + 绝对定位元素实际占用宽度;
- 定位参照对象的高度 = top + bottom + margin-top + margin-bottom + 绝对定位元素实际占用高度;
.father {
position: relative;
}
.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
2.absolute+translate(未知宽高)
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3.absoute+translate(已知宽高)
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;//设宽高为100px
margin-top: -50px;
}
4.flex布局
.warp {
background-color: #FF8C00;
width: 200px;
height: 200px;
display: flex;
justify-content: center; /*使子项目水平居中*/
align-items: center; /*使子项目垂直居中*/
}
.example3 {
background-color: #F00;
width: 100px;
height: 100px;
}
5.relative+translateY
.warp {
position: relative;
background-color: orange;
width: 200px;
height: 200px;
}
.example3 {
position: relative;
top:50%;
transform:translateY(-50%);
background-color: red;
width: 100px;
height: 100px;
margin: 0 auto;
}
阅读剩余
版权声明:
作者:chun
链接:https://chun53.top/407.html
文章版权归作者所有,未经允许请勿转载。
THE END