水平居中:
-
行内级元素:
- 设置父元素的
text-align: center
- 设置父元素的
-
块级元素:
- 设置当前块级元素(宽度)
margin: 0 auto;
- 设置当前块级元素(宽度)
-
绝对定位
- 元素有宽度情况下,
left0/right0/margin: 0 auto;
- 元素有宽度情况下,
-
flex
-
justify-content: center
-
垂直居中:
-
绝对定位
-
元素有高度情况下,
top0/bottom0/margin: auto 0;
- 弊端:
- 必须使用定位(脱离标准流)
- 必须给元素设置高度
-
-
flex布局(父元素设置flex)
align-items: center;- 弊端:
- 当前flex局部中所有的元素都会被垂直居中
- 相对来说, 兼容性差一点点(基本可以忽略)
-
top/translate
/* 两件事情: 1.让元素向下位移父元素的50% 2.让元素向上位移自身的50% */ position: relative; top: 50%; transform: translate(0, -50%);