温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CSS3如何制作弹性盒子

发布时间:2026-08-30 13:38:56 来源:亿速云 阅读:84 作者:小樊 栏目:编程语言

在 CSS3 中,弹性盒子(Flexbox) 主要通过 display: flex 来创建,用来实现一维(横向或纵向)的弹性布局。下面从基本用法 → 常用属性 → 示例一步步说明。


一、创建弹性盒子(Flex Container)

.container {
  display: flex; /* 或 display: inline-flex */
}

只要给父元素设置 display: flex,它就变成了一个 弹性容器(flex container),其直接子元素自动成为 弹性子项(flex items)

<div class="container">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>

二、主轴与交叉轴(核心概念)

  • 主轴(main axis):默认是 水平方向
  • 交叉轴(cross axis):默认是 垂直方向

方向由 flex-direction 决定。


三、常用弹性容器属性

1️⃣ flex-direction(主轴方向)

.container {
  flex-direction: row;            /* 默认:从左到右 */
  flex-direction: row-reverse;    /* 从右到左 */
  flex-direction: column;         /* 从上到下 */
  flex-direction: column-reverse; /* 从下到上 */
}

2️⃣ 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;  /* 均匀间距 */
}

3️⃣ align-items(交叉轴对齐方式)

.container {
  align-items: stretch;      /* 默认:拉伸 */
  align-items: flex-start;   /* 顶部对齐 */
  align-items: flex-end;     /* 底部对齐 */
  align-items: center;       /* 垂直居中 */
  align-items: baseline;     /* 基线对齐 */
}

4️⃣ flex-wrap(是否换行)

.container {
  flex-wrap: nowrap;   /* 默认:不换行 */
  flex-wrap: wrap;     /* 换行 */
  flex-wrap: wrap-reverse;
}

5️⃣ align-content(多行对齐)

只在 flex-wrap: wrap 且有多行时生效

.container {
  align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}

四、常用弹性子项属性

1️⃣ flex(最常用)

.item {
  flex: 1; /* 等分剩余空间 */
}

等价于:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;

2️⃣ flex-grow(放大比例)

.item {
  flex-grow: 1; /* 默认 0,不放大 */
}

3️⃣ flex-shrink(缩小比例)

.item {
  flex-shrink: 1; /* 默认 1,允许缩小 */
}

4️⃣ flex-basis(初始大小)

.item {
  flex-basis: 200px;
}

5️⃣ align-self(单独对齐)

.item {
  align-self: center;
}

五、完整示例

示例 1:水平居中 + 等分宽度

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

.item {
  flex: 1;
  text-align: center;
}

示例 2:垂直居中布局

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

示例 3:响应式导航栏

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav a {
  flex: 1;
  text-align: center;
}

六、Flexbox 适用场景

✅ 导航栏
✅ 卡片布局
✅ 居中(水平 / 垂直)
✅ 自适应宽度布局

❌ 复杂二维布局(推荐使用 Grid)


如果你愿意,我可以:

  • ✅ 用 图示解释主轴 / 交叉轴
  • ✅ 对比 Flex vs Grid
  • ✅ 给你一个 实战小项目(如响应式布局)
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI