垂直居中,你知道多少

常见垂直居中方式

相对定位

1
2
3
4
5
6
7
8
9
10
.content {
position: relative;
top: 50%; //垂直居中
margin:0 auto;//水平居中
margin-top: -100px;//减去自身的高度一半

background-color: #6699FF;
width: 200px;
height: 200px;
}

绝对定位:

1
2
3
4
5
6
7
8
9
10
content{
width: 300px;
height: 300px;
background: orange;

position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);//CSS3新特性 不需要知道自身宽高
}

Flex布局

父容器:

1
2
3
4
5
wrapper{
justify-content: center;//项目在主轴上的对齐方式(X)
align-items: center; //项目在交叉轴上如何对齐
display: -webkit-flex;
}

fixed

1
2
3
4
5
6
7
div {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

补充点定位

absolute

  • 绝对定位脱离文档流,相对于父级不为static的元素定位
  • 文档流就是按照从左到右,从上到下的顺序排列的页面结构

relative

  • 想对定位是相对于自身原来的位置定位,原来的位置还是占着文档流的空间

float

  • 脱离文档流,clear的含义是当前元素的某个位置没有浮动元素
谢谢你请我喝咖啡