2023-10-27 23:56:40
使用 CSS Flexbox 实现水平垂直居中,核心是通过父容器设置 Flex 布局并启用居中对齐属性,以下是具体实现方法及要点:
基础实现代码
.container { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ height: 100vh; /* 视口高度(或指定具体高度) */}或使用 min-height 增强兼容性(内容较少时仍居中):
.container { display: flex; justify-content: center; align-items: center; min-height: 100vh; /* 最小高度为视口高度 */}关键属性解析
适用场景
注意事项
示例:若父元素为 <div class="container"></div> 且未设置高度,子元素会紧贴顶部。
浏览器兼容性Flexbox 布局在现代浏览器中广泛支持(Chrome、Firefox、Safari、Edge 等),包括移动端。对于极旧版本浏览器(如 IE 10 以下),需添加前缀或使用替代方案(如 transform: translate(-50%, -50%) 结合绝对定位)。
完整示例
<!DOCTYPE html><html><head> <style> .container { display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #f0f0f0; } .box { width: 200px; height: 100px; background-color: #4CAF50; color: white; display: flex; justify-content: center; align-items: center; border-radius: 8px; } </style></head><body> <div class="container"> <div class="box">居中内容</div> </div></body></html>此示例中,绿色盒子会在页面中完美水平垂直居中,且适应不同屏幕尺寸。
总结Flexbox 的 justify-content: center 和 align-items: center 组合是实现水平垂直居中的最简洁、可靠方案,适用于大多数现代布局需求。通过合理设置父容器高度(如 min-height: 100vh),可确保内容较少时依然居中,推荐作为首选方法。