水平垂直居中的几种方法(总结)
-
1.使用 flexbox 的 justify-content 和 align-items
-
.parent {display: flex;justify-content: center; /* 水平居中 */align-items: center; /* 垂直居中 */height: 100vh; /* 需要指定高度 */ }
-
2.使用 grid 的 place-items: center
-
.parent {display: grid;place-items: center; /* 水平和垂直同时居中 */height: 100vh; }
-
3.使用 position: absolute 和 transform
-
.parent {position: relative;height: 100vh; }.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%); }
-
4.使用 table-cell 和 vertical-align: middle
-
.parent {display: table;width: 100%;height: 100vh;text-align: center; /* 水平居中 */ }.child {display: table-cell;vertical-align: middle; /* 垂直居中 */ }
PS:基本没用过,这个太老了
-
5.使用 margin: auto(子元素固定宽高)
-
.parent {display: block;height: 100vh; }.child {width: 200px;height: 200px;margin: auto; }
-
6.使用 line-height 和 text-align: center(仅限单行文本)
-
.parent {height: 100vh;line-height: 100vh; /* 行高等于容器高度 */text-align: center; /* 水平居中 */ }.child {display: inline-block;vertical-align: middle; }
-
7.使用 inline-block 和 text-align: center
-
.parent {text-align: center; /* 水平居中 */height: 100vh; }.child {display: inline-block;vertical-align: middle; /* 垂直居中 */margin: auto; }
-
8.使用 min-height 和 min-width + flexbox
-
.parent {display: flex;justify-content: center; /* 水平居中 */align-items: center; /* 垂直居中 */min-height: 100vh; }.child {min-width: 200px;min-height: 200px; }
-
9.使用 vh 单位
-
.parent {height: 100vh;display: flex;justify-content: center; /* 水平居中 */align-items: center; /* 垂直居中 */ }
-
10.使用 absolute + display: flex(嵌套居中)
-
.parent {position: relative;height: 100vh; }.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);display: flex;justify-content: center;align-items: center; }
-
11.使用 display: block 和 margin: auto(适用于固定宽高的元素)
-
.parent {display: block;height: 100vh; }.child {width: 200px;height: 200px;margin: auto; }
-
12.使用 text-indent 和 white-space: nowrap(适用于文字)
-
.parent {text-align: justify;white-space: nowrap;text-indent: 50%;transform: translateX(-50%);height: 100vh; }