Flex 布局是现代 Web 开发中必不可少的布局方案。本文将结合代码示例详解 Flex 布局的核心特性,助你快速掌握这一强大工具。
一、弹性盒子基础
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
<style>
.container {
display: flex; /* 启用弹性盒子 */
border: 2px solid #ccc;
padding: 10px;
}
.item {
padding: 20px;
background: #3498db;
color: white;
margin: 5px;
}
</style>
二、主轴对齐方式(justify-content)
/* 默认效果 */
.container {
justify-content: flex-start;
}
/* 居中对齐 */
.center {
justify-content: center;
}
/* 两端对齐 */
.space-between {
justify-content: space-between;
}
三、侧轴对齐方式(align-items)
/* 垂直居中 */
.container {
height: 200px;
align-items: center;
}
/* 单独设置某个元素 */
.special-item {
align-self: flex-end;
}
四、更改主轴方向(flex-direction)
/* 垂直排列 */
.vertical {
flex-direction: column;
}
/* 反向排列 */
.reverse {
flex-direction: row-reverse;
}
五、弹性比例(flex)
<div class="flex-container">
<div class="item" style="flex: 1">1份</div>
<div class="item" style="flex: 2">2份</div>
<div class="item" style="flex: 1">1份</div>
</div>
六、换行与多行对齐(flex-wrap + align-content)
.wrap-container {
flex-wrap: wrap;
height: 300px;
align-content: space-around;
}
.item {
width: 30%; /* 强制换行 */
}
七、综合案例:响应式导航栏
<nav class="navbar">
<div class="logo">LOGO</div>
<div class="menu">
<a href="#">首页</a>
<a href="#">产品</a>
<a href="#">关于</a>
<a href="#">联系</a>
</div>
<div class="user">用户</div>
</nav>
<style>
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
background: #f8f9fa;
}
.menu {
display: flex;
gap: 20px; /* 项目间距 */
}
@media (max-width: 768px) {
.navbar {
flex-direction: column;
align-items: stretch;
}
.menu {
flex-direction: column;
text-align: center;
}
}
</style>
八、Flex 布局速查表
属性 | 常用值 | 说明 |
---|---|---|
display | flex | 创建弹性容器 |
flex-direction | row/column | 主轴方向 |
justify-content | space-between | 主轴对齐 |
align-items | center | 侧轴对齐 |
flex-wrap | wrap | 允许换行 |
flex | 1/2/3 | 分配剩余空间 |
九、最佳实践技巧
- 优先使用
gap
属性设置项目间距 - 组合使用
flex: 1
实现等分布局 - 响应式布局配合媒体查询修改
flex-direction
- 使用
min-width
防止内容过度挤压
图片来源:
建议通过 Chrome DevTools 的 Flexbox 调试工具实时观察布局变化,这将极大提升学习效率。