📝 前端课堂笔记:CSS Flex 布局 + 表单实战详解
一、为什么学 Flex?—— 解决传统布局痛点
以前我们用 float、position 做布局,经常遇到:
• 元素对齐困难
• 响应式适配麻烦
• 垂直居中要写一堆 hack
Flex 布局 就是为了解决这些问题而生的!它通过“弹性容器 + 弹性项目”的模型,让布局变得像搭积木一样简单。
二、Flex 核心概念(先搞懂这几个词)
术语 含义
弹性容器(Flex Container) 设置了 display: flex 的父元素
弹性项目(Flex Item) 容器内的子元素
主轴(Main Axis) 项目排列的方向(默认水平从左到右)
交叉轴(Cross Axis) 垂直于主轴的方向(默认垂直从上到下)
✅ 记住:主轴决定“怎么排”,交叉轴决定“怎么对齐”
三、Flex 容器常用属性(6个核心)
1️⃣ flex-direction —— 控制主轴方向
.container {
flex-direction: row; /* 默认:从左到右 /
flex-direction: row-reverse; / 从右到左 /
flex-direction: column; / 从上到下 /
flex-direction: column-reverse; / 从下到上 */
}
💡 想象成“排队方向”:横排 or 竖排?正着排 or 倒着排?
2️⃣ justify-content —— 主轴上的对齐方式
.container {
justify-content: flex-start; /* 左对齐(默认) /
justify-content: flex-end; / 右对齐 /
justify-content: center; / 居中 /
justify-content: space-between;/ 两端对齐,中间均分 /
justify-content: space-around; / 每个项目两侧间隔相等 */
}
🎯 应用场景:导航栏居中、卡片横向均匀分布、底部按钮靠右等
3️⃣ align-items —— 交叉轴上的对齐方式
.container {
align-items: flex-start; /* 顶部对齐 /
align-items: flex-end; / 底部对齐 /
align-items: center; / 垂直居中(最常用!) /
align-items: baseline; / 文字基线对齐 /
align-items: stretch; / 默认:撑满容器高度 */
}
🧭 记住:center 是万能钥匙,垂直居中用它准没错!
4️⃣ flex-wrap —— 是否允许换行
.container {
flex-wrap: nowrap; /* 不换行(默认) /
flex-wrap: wrap; / 换行,第一行在上 /
flex-wrap: wrap-reverse; / 换行,第一行在下 */
}
⚠️ 注意:如果容器宽度不够,不换行会导致项目被压缩!
5️⃣ align-content —— 多行时的交叉轴对齐(单行无效)
.container {
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
📌 只有当项目换行了(比如 flex-wrap: wrap),这个属性才生效!
6️⃣ flex-flow —— 简写属性
.container {
flex-flow: row wrap; /* 相当于 flex-direction: row; flex-wrap: wrap; */
}
✍️ 推荐写法:简洁高效,开发中常用。
四、实战案例:登录表单布局(Flex 的经典应用)
我们来实现一个美观的登录表单:
✅ HTML 结构
✅ CSS 样式(重点看 Flex 怎么用)
.login-form {
width: 400px;
margin: 20px auto;
font-family: "Microsoft YaHei", sans-serif;
border: 1px solid #ccc;
padding: 20px;
background: #fff;
}
.form-header {
text-align: center;
font-size: 24px;
font-weight: bold;
padding: 10px 0;
border-bottom: 1px solid #ccc;
margin-bottom: 15px;
}
.form-row {
display: flex;
align-items: center;
margin-bottom: 15px;
border: 1px solid #ccc;
padding: 8px;
border-radius: 4px;
}
.form-row label:first-child {
width: 80px;
text-align: right;
margin-right: 10px;
font-weight: bold;
}
.form-row input[type="text"],
.form-row input[type="password"] {
flex: 1;
padding: 6px;
border: none;
outline: none;
}
.form-row input[type="radio"] {
margin-right: 4px;
}
🔍 关键点解析:
• .form-row { display: flex; } → 让每一行变成弹性容器
• align-items: center → 标签和输入框垂直居中
• flex: 1 → 输入框自动占满剩余空间
• label:first-child { width: 80px } → 固定标签宽度,保证对齐
✅ 这样写出来的表单:结构清晰、响应式友好、易维护
五、今日收获总结
✅ 理解了 Flex 的核心思想:主轴 + 交叉轴 + 弹性项目
✅ 掌握了 6 个核心属性及其实际应用场景
✅ 能用 Flex 快速实现表单、导航、卡片布局
✅ 学会了用 flex: 1 和 align-items: center 解决常见对齐问题

浙公网安备 33010602011771号