水平居中、垂直居中
水平居中
- inline行内元素:其父元素设置
text-align: center
- block块元素:
margin: auto
(自身要有宽度) - absolute:
left: 50% + margin-left负值(自身宽度一半)
垂直居中
- inline元素:
line-height: height
- absolute元素:
top: 50% + margin-top为负值(自身高度的一半)
- absolute元素:
top: 50% + transform(-50%, -50%)
- absolute元素:
top left right bottom = 0, + margin: auto
水平垂直居中
1.设置父元素为相对定位,给子元素设置绝对定位,
top: 0; right: 0; bottom: 0; left: 0; margin: auto;
2.设置父元素为相对定位,给子元素设置绝对定位,
left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%)/transform(-50%, -50%)
3.设置父元素为flex定位,
justify-content: center; align-items: center;
4.设置父元素绝对定位,给子元素设置绝对定位
left 50%; top: 50%; margin-left: 一半的宽度; margin-top: 一半的高度
transform和flex都是css3中的内容