回顾几种常用到的css居中方案,从最常用的说起:
1. 单行文本的垂直水平居中
/* line-height: 设置为盒子的高度*/ line-height: 200px; text-align: center;
2. display: flex;实现的盒子内部垂直水平居中:
display: flex; align-items: center; justify-content: center;
3. position: absolute;实现的盒子在其他盒子中垂直水平居中:
position: absolute; top: 50%; left: 50%; /* margin负盒子自身宽高的一半 */ margin-top: -100px; margin-left: -100px;
4. 若是不知道自身盒子的宽高,那么可以运用transform: translate(-50%,-50%):
position: absolute; top: 50%; left: 50%; /* margin负盒子自身宽高的一半 */ /* margin-top: -100px; margin-left: -100px; */ transform: translate(-50%,-50%);
5. 若是盒子宽高固定,那么可以:
position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto;
6. table实现盒子的居中,为其嵌套一层父级盒子,父级盒子设置display: table;自身设置display: table-cell;vertical-align: middle;
.outer { width: 600px; height: 600px; margin-top: 100px; margin-left: 500px; background: palegoldenrod; display: table; } .inner { width: 200px; height: 200px; /* line-height: 设置为盒子的高度*/ line-height: 200px; text-align: center; background: deepskyblue; display: table-cell; vertical-align: middle; }
以上便是我常用到的垂直水平居中方法
原文:https://www.cnblogs.com/qlongbg/p/12193215.html