目录
1. 使用Flex布局
2. 使用Grid布局
3.绝对定位 + 负外边距 (必须知晓盒子的具体大小)
4.绝对定位+外边距 auto
5.绝对定位 + transform (无须知晓盒子的具体大小)
如何实现:
在父元素上添加:
display: flex;
align-items: center;
justify-content: center;
我要水平垂直居中
如何实现:
在父元素上添加:
display: grid;
place-items: center;
我要水平垂直居中
相对父级上边和左边,或者下边和右边各移动50%,同时通过外边距减去自身的宽高各一半的大小。
如何实现:
在父元素上添加:
position: relative;
在子元素上添加:
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px; //子元素高度的一半
margin-left: -100px; //子元素宽度的一半
我要水平垂直居中
将盒子的上下左右定位全部设置为0,同时设置外边距自适应
如何实现:
在父元素上添加:
position: relative;
在子元素上添加:
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
我要水平垂直居中
使用CSS3中的新属性transform: translate(-50%,-50%); 来直接减去盒子自身的50%大小
如何实现:
在父元素上添加:
position: relative;
在子元素上添加:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
我要水平垂直居中