Tutorial·  

CSS Flexbox 布局详解

Flexbox 是 CSS 中强大的布局系统,让创建复杂的响应式布局变得简单。

W3C

@W3C

什么是 Flexbox?

Flexbox(弹性盒子布局)是一种用于在页面上布置元素的布局模式,它能够使元素具有灵活的行为,能够适应不同的屏幕尺寸和设备。

基本概念

Flexbox 涉及两个主要概念:

  1. Flex 容器:父元素,设置 display: flex
  2. Flex 项目:容器内的直接子元素

基本用法

创建 Flex 容器

.container {
    display: flex;
}

主轴和交叉轴

  • 主轴(Main Axis):Flex 项目排列的主要方向
  • 交叉轴(Cross Axis):垂直于主轴的方向

常用属性

容器属性

flex-direction:设置主轴方向

.container {
    flex-direction: row;        /* 水平方向(默认) */
    flex-direction: row-reverse; /* 水平方向,反向 */
    flex-direction: column;     /* 垂直方向 */
    flex-direction: column-reverse; /* 垂直方向,反向 */
}

justify-content:设置主轴上的对齐方式

.container {
    justify-content: flex-start;    /* 起点对齐 */
    justify-content: flex-end;      /* 终点对齐 */
    justify-content: center;        /* 居中对齐 */
    justify-content: space-between; /* 两端对齐 */
    justify-content: space-around;  /* 环绕对齐 */
    justify-content: space-evenly;  /* 均匀分布 */
}

align-items:设置交叉轴上的对齐方式

.container {
    align-items: stretch;   /* 拉伸(默认) */
    align-items: flex-start;/* 起点 */
    align-items: flex-end;  /* 终点 */
    align-items: center;    /* 居中 */
    align-items: baseline;  /* 基线 */
}

项目属性

flex-grow:定义项目的放大比例

.item {
    flex-grow: 0;   /* 不放大(默认) */
    flex-grow: 1;   /* 等分剩余空间 */
    flex-grow: 2;   /* 占 2 份剩余空间 */
}

flex-shrink:定义项目的缩小比例

.item {
    flex-shrink: 1; /* 可以缩小(默认) */
    flex-shrink: 0; /* 不缩小 */
}

flex-basis:定义项目的主轴尺寸

.item {
    flex-basis: auto;  /* 自动(默认) */
    flex-basis: 200px; /* 固定宽度 */
}

实用示例

水平居中

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}

三栏布局

.container {
    display: flex;
    justify-content: space-between;
}

.sidebar {
    flex: 1;
}

.content {
    flex: 3;
}

学习资源

点评

点赞或评论
加载评论中...