html-css-display: flex 完整使用说明

display: flex 完整使用说明
一、基础概念
display: flex 给父容器设置,开启弹性布局;子元素自动成为弹性项 (flex-item)。
注意:样式写在父盒子上,不要写在子元素!
css
.box { display: flex; /* 开启弹性布局 */}
二、父容器(flex 容器)常用属性
1. flex-direction:主轴方向
css
flex-direction: row; /* 默认,水平从左→右 */
flex-direction: row-reverse; /* 水平 右→左 */
flex-direction: column; /* 垂直 上→下 */
flex-direction: column-reverse;/* 垂直 下→上 */

2. flex-wrap:是否换行
css
flex-wrap: nowrap; /* 默认,不换行,子元素压缩挤在一行 */
flex-wrap: wrap; /* 空间不足自动换行 */
flex-wrap: wrap-reverse; /* 换行,行顺序反转 */

3. flex-flow 简写 = flex-direction + flex-wrap
css
flex-flow: row wrap;
4. justify-content:主轴对齐(水平默认主轴)
css
justify-content: flex-start; /* 默认,靠起点 */
justify-content: flex-end; /* 靠终点 */
justify-content: center; /* 居中 */
justify-content: space-between; /* 两端对齐,子元素之间均分空隙 */
justify-content: space-around; /* 每个元素左右都有同等空隙 */
justify-content: space-evenly; /* 所有间隙完全相等 */

5. align-items:单行交叉轴对齐(垂直方向)
css
align-items: stretch; /* 默认,拉伸填满容器高度 */
align-items: flex-start; /* 顶部对齐 */
align-items: flex-end; /* 底部对齐 */
align-items: center; /* 垂直居中 */
align-items: baseline; /* 按文字基线对齐 */

6. align-content:多行弹性项交叉轴对齐(只有开启 wrap 换行才生效)
css
align-content: stretch;
align-content: center;
align-content: flex-start;
align-content: flex-end;
align-content: space-between;
align-content: space-around;

三、子元素(flex-item)属性
1. flex-grow:剩余空间分配(放大比例)
默认 0,不放大;数值越大分得越多空白区域
css
.item { flex-grow: 1; /* 所有子元素均分剩余宽度 */ }
2. flex-shrink:空间不足时缩小比例
默认 1,空间不够会自动缩小;设为 0 禁止缩小
css
flex-shrink: 0;
3. flex-basis:弹性项基准尺寸
相当于弹性布局下的初始宽 / 高,优先级高于 width
css
flex-basis: 200px;
4. flex 简写:flex: grow shrink basis
css
flex: 1; /* 等价 flex:1 1 0%; 均分空间,最常用 */
flex: 0 1 auto;/* 默认值 */
flex: 0 0 150px; /* 固定尺寸,不放大不缩小 */

5. align-self:单独控制某个子元素交叉轴对齐
覆盖父容器 align-items
css
align-self: center | flex-start | flex-end | stretch;
6. order:控制子元素排序
默认 0,数值越小越靠前,可以负数
css
order: -1; /* 跑到最前面 */
四、高频实用示例
示例 1:水平垂直居中(最常用)
css
.box {
width: 400px;
height: 300px;
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}

示例 2:导航栏,均匀分布、自动换行
css
.nav { display: flex; flex-wrap: wrap; justify-content: space-between; }
示例 3:左右固定,中间自适应布局
html
预览

<div class="wrap">
  <div class="left">左</div>
  <div class="main">自适应中间</div>
  <div class="right">右</div>
</div>

css

.wrap {  display: flex;}
.left,.right {  flex: 0 0 120px; /* 固定宽度,不缩放 */}
.main {  flex: 1; /* 自动占满剩余空间 */}

五、常见坑点
浮动 float、vertical-align 对 flex-item 失效
弹性子元素默认不会文字自动换行,长文本需要手动加 word-break:break-all
align-content 多行才生效,单行无效,别和 align-items 搞混
flex-basis > width;如果设置 flex-basis,width 可能失效
弹性容器内的文本节点也会被当作弹性项

Leave a Reply

Your email address will not be published. Required fields are marked *