水平居中
- 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; }
博客介绍了CSS中元素水平和垂直居中的方法。水平居中方面,inline元素用text-align: center;,block元素用margin: auto;,absolute元素用left: 50%加margin-left负值。垂直居中方面,inline元素可使line-height等于height,还可采用flex布局、absolute和负margin等方法。
176

被折叠的 条评论
为什么被折叠?



