基本概念
flex布局默认表现
不换【
flex-wrap:no-wrap】flex item 垂直方向上填充父容器(flex item 没有设置高度)【
align-items:stretch】空间不够时会进行压缩,空间充足时不会伸长【
flex:0 1 auto】
flex-direction
主轴的方向
| 值 | 主轴方向 | 子项排列方向 | 说明 |
|---|---|---|---|
row | 默认,水平(从左到右) | 👉 → | 默认值 |
column | 垂直(从上到下) | 👇 ↓ | 元素竖着排列 |
justify-content
justify-content 是 Flex 布局 中用来控制 主轴(main axis)上子元素的对齐方式 的属性。
| 值 | 对齐方向 | 效果说明 |
|---|---|---|
flex-start | 起点对齐(默认) | 所有子项都靠主轴起点排列(左或上) |
flex-end | 终点对齐 | 所有子项都靠主轴终点排列(右或下) |
center | 居中对齐 | 所有子项在主轴中间集中 |
space-between | 两端对齐 | 第一个在起点,最后一个在终点,中间平均分配空间 |
space-around | 环绕分布 | 每个子项两侧都有相等间距(两边看起来有半个间距) |
space-evenly | 平均分布 | 所有间距(包括两边)都相等 |
align-items
align-items 是 Flex 布局 中用于控制 交叉轴(cross axis)上子元素的对齐方式 的属性。
| 值 | 对齐方向 | 效果说明 |
|---|---|---|
stretch | 拉伸(默认值) | 若子元素未设置高度(主轴:row),会被拉伸以填满容器 |
flex-start | 交叉轴起点对齐 | 子项都靠交叉轴的起点(如上方)对齐 |
flex-end | 交叉轴终点对齐 | 子项都靠交叉轴的终点(如下方)对齐 |
center | 居中对齐 | 子项在交叉轴中间居中 |
baseline | 基线对齐 | 子项的文本基线(文字底部)对齐 |
gap
gap 是 CSS Flexbox 和 Grid 布局中用于控制子元素之间间距的属性。 以前我们常用 margin 来手动添加间距,现在用 gap 更简单、语义更清晰。
css
gap: <row-gap> <column-gap>;使用 margin控制元素之间的距离,需要手动去掉最后一个元素的 margin-right,否则会多出空隙:
css
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<style>
.container {
display: flex;
}
.container > div {
margin-right: 20px;
}
.container > div:last-child {
margin-right: 0;
}
</style>css
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<style>
.container {
display: flex;
gap: 20px;
}
</style>