水平居中
- inline元素:text-align: center;
- block元素:margin: auto;
- absolute元素:left: 50% + margin-left 负值;
垂直居中
- inline元素:line-height的值等于height的值;
- flex布局;
// 父元素 .father { display: flex; align-items:Center; } // 或者 .father { display: flex; flex-direction:column; justify-content:center; }
- absolute和负margin(子元素需要确定宽高);
// 父元素 .father { position: relative; } // 子元素 .child { position: absolute; width: 100px; height: 50px; top: 50%; left: 50%; margin-left: -50px; margin-top: -25px; text-align: center; }
- translate;
// 父元素 .father { position: relative; } // 子元素 .box { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); text-align: center; }
- absolute和margin:auto;
// 父元素 .father { position: relative; } // 子元素 .child { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }