Flex 弹性布局
Flexbox(弹性布局)是一维布局模型,擅长处理"一行内如何排列、对齐、分配空间"。给容器设置 display: flex 后,其子元素自动变成弹性项。
容器属性
flex-direction:主轴方向 row(默认)/ column;justify-content:主轴对齐方式(center、space-between 等);align-items:交叉轴对齐方式;flex-wrap:是否换行。
项目属性
flex: 1 让项目按比例分配剩余空间;flex-grow 控制放大比例。经典用法:justify-content: space-between 实现两端对齐的导航栏。
代码示例
<style>
.navbar {
display: flex;
justify-content: space-between; /* 两端对齐 */
align-items: center;
padding: 12px 20px;
background: #1a1b1c;
color: #fff;
}
.cards {
display: flex;
gap: 16px; /* 间距 */
flex-wrap: wrap;
}
.card {
flex: 1 1 180px; /* 可伸缩,基础宽度 180px */
padding: 16px;
background: #f0f4ff;
border-radius: 8px;
text-align: center;
}
</style>
<div class="navbar">
<strong>LOGO</strong>
<span>首页</span><span>教程</span><span>关于</span>
</div>
<div class="cards">
<div class="card">卡片 1</div>
<div class="card">卡片 2</div>
<div class="card">卡片 3</div>
</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
color: #333; | 文字颜色 |
background: #fff; | 背景色 / 背景图 |
font-size: 16px; | 字号 |
font-family: Arial; | 字体 |
font-weight: bold; | 字重(加粗) |
margin: 10px; | 外边距(上右下左) |
padding: 10px; | 内边距 |
border: 1px solid #ccc; | 边框:粗细 样式 颜色 |
border-radius: 8px; | 圆角 |
width: 100%; | 宽度 |
height: 200px; | 高度 |
display: flex; | 弹性布局(现代布局主力) |
display: none; | 隐藏元素 |
position: relative / absolute / fixed; | 定位方式 |
top / left / right / bottom | 定位偏移 |
text-align: center; | 文字水平对齐 |
line-height: 1.6; | 行高 |
overflow: hidden; | 内容溢出处理 |
box-shadow: 0 2px 8px rgba(0,0,0,.1); | 阴影 |
transition: all .3s; | 过渡动画 |
cursor: pointer; | 鼠标手型 |
z-index: 10; | 层叠顺序 |
max-width: 1200px; margin: 0 auto; | 容器居中(经典写法) |
@media (max-width: 768px) {} | 响应式断点 |
:hover | 鼠标悬停状态 |