Flexbox 详解
Flexbox(弹性盒)是 CSS3 最重要的一维布局方案,解决水平垂直居中、等分、自适应排列这些问题,一行代码搞定。
容器属性
父元素设 display: flex 后:
flex-direction:主轴方向,row 横排 / column 竖排justify-content:主轴对齐,center 居中 / space-between 两端align-items:交叉轴对齐,center 垂直居中flex-wrap:是否换行gap:子元素间距
子元素属性
flex:简写flex: 增长 缩小 基础尺寸,如 flex: 1 等分align-self:单独覆盖对齐方式
代码示例
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
/* 经典垂直居中 */
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
}
/* 三列等分 */
.columns {
display: flex;
gap: 16px;
}
.columns > div {
flex: 1;
}
📚 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 | 鼠标悬停状态 |