在 CSS3 中,弹性盒子(Flexbox) 主要通过 display: flex 来创建,用来实现一维(横向或纵向)的弹性布局。下面从基本用法 → 常用属性 → 示例一步步说明。
.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>
方向由 flex-direction 决定。
.container {
flex-direction: row; /* 默认:从左到右 */
flex-direction: row-reverse; /* 从右到左 */
flex-direction: column; /* 从上到下 */
flex-direction: column-reverse; /* 从下到上 */
}
.container {
justify-content: flex-start; /* 默认:起点对齐 */
justify-content: flex-end; /* 终点对齐 */
justify-content: center; /* 居中 */
justify-content: space-between; /* 两端对齐 */
justify-content: space-around; /* 等间距 */
justify-content: space-evenly; /* 均匀间距 */
}
.container {
align-items: stretch; /* 默认:拉伸 */
align-items: flex-start; /* 顶部对齐 */
align-items: flex-end; /* 底部对齐 */
align-items: center; /* 垂直居中 */
align-items: baseline; /* 基线对齐 */
}
.container {
flex-wrap: nowrap; /* 默认:不换行 */
flex-wrap: wrap; /* 换行 */
flex-wrap: wrap-reverse;
}
只在
flex-wrap: wrap且有多行时生效
.container {
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
.item {
flex: 1; /* 等分剩余空间 */
}
等价于:
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;
.item {
flex-grow: 1; /* 默认 0,不放大 */
}
.item {
flex-shrink: 1; /* 默认 1,允许缩小 */
}
.item {
flex-basis: 200px;
}
.item {
align-self: center;
}
.container {
display: flex;
justify-content: center;
}
.item {
flex: 1;
text-align: center;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
.nav a {
flex: 1;
text-align: center;
}
✅ 导航栏
✅ 卡片布局
✅ 居中(水平 / 垂直)
✅ 自适应宽度布局
❌ 复杂二维布局(推荐使用 Grid)
如果你愿意,我可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。