如何实现水平垂直居中?至少列举三种方法。
介绍使用 Flex、Grid 布局和绝对定位三种方法实现网页内容的水平和垂直居中。
- Flex 布局方法:父元素设置弹性布局模式,通过
justify-content
和align-items
实现居中:.parent { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ height: 100vh; }
子元素无额外样式,兼容性好且无需固定宽高。
- Grid 布局方法:父元素开启网格布局,使用
place-items: center
一站式居中:.parent { display: grid; place-items: center; /* 水平垂直居中 */ height: 100vh; }
现代浏览器支持良好,代码简洁。
- 绝对定位 + Transform:子元素绝对定位后平移自身宽高 50%:
.parent { position: relative; height: 100vh; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* 自身尺寸补偿 */ }
无需知子元素宽高,兼容性佳(IE9+)。