温馨提示×

温馨提示×

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

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

css3怎么写弹性盒子布局

发布时间:2026-09-18 22:34:05 来源:亿速云 阅读:96 作者:小樊 栏目:编程语言

在 CSS3 中,**弹性盒子布局(Flexbox)**主要通过 display: flex 来实现,用来更方便地控制子元素在容器中的排列、对齐和空间分配。

下面从 基本用法 → 常用属性 → 示例 一步步说明。


一、开启弹性盒子

.container {
  display: flex;
}

或者:

.container {
  display: inline-flex;
}

flex:块级弹性容器
inline-flex:行内弹性容器


二、容器(父元素)常用属性

1️⃣ 主轴方向 flex-direction

.container {
  flex-direction: row;        /* 默认,水平 */
  /* row-reverse | column | column-reverse */
}

2️⃣ 是否换行 flex-wrap

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

3️⃣ 主轴对齐 justify-content

.container {
  justify-content: flex-start; /* 默认 */
  /* flex-end | center |
     space-between | space-around | space-evenly */
}

4️⃣ 交叉轴对齐 align-items

.container {
  align-items: stretch; /* 默认 */
  /* flex-start | flex-end | center | baseline */
}

5️⃣ 多行对齐 align-content

(仅在 flex-wrap: wrap 时生效)

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

三、子元素(项目)常用属性

1️⃣ 放大比例 flex-grow

.item {
  flex-grow: 1; /* 默认 0 */
}

2️⃣ 缩小比例 flex-shrink

.item {
  flex-shrink: 1; /* 默认 */
}

3️⃣ 基础大小 flex-basis

.item {
  flex-basis: 100px;
}

4️⃣ 简写 flex

.item {
  flex: 1;            /* grow */
  /* flex: 1 1 auto; */
}

5️⃣ 单独对齐 align-self

.item {
  align-self: center;
}

四、完整示例

HTML

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

CSS

.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100px;
  background: #f0f0f0;
}

.item {
  width: 50px;
  height: 50px;
  background: skyblue;
}

五、常见布局示例

✅ 水平垂直居中

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

✅ 两端对齐

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

✅ 等分布局

.item {
  flex: 1;
}

如果你有具体布局需求(比如导航栏、卡片列表、移动端布局),可以直接说,我可以帮你写完整代码。

向AI问一下细节

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

AI
助
手