Flex 的 多种对齐属性
1. html 结构
<div id="container"> <div class="item item-1"> <h3>Item 1</h3> </div> <div class="item item-2"> <h3>Item 2</h3> </div> <div class="item item-3"> <h3>Item 3</h3> </div> </div>
<div class="item item-3">
<h3>Item 3</h3>
</div>
<div class="item item-1">
<h3>Item 1</h3>
</div>
<div class="item item-2">
<h3>Item 2</h3>
</div>
<div class="item item-3">
<h3>Item 3</h3>
</div>
<div class="item item-1">
<h3>Item 1</h3>
</div>
<div class="item item-2">
<h3>Item 2</h3>
</div>
<div class="item item-3">
<h3>Item 3</h3>
</div>
<div class="item item-1">
<h3>Item 1</h3>
</div>
<div class="item item-2">
<h3>Item 2</h3>
</div>
<div class="item item-3">
<h3>Item 3</h3>
</div>
2. css 样式
#container { display: flex; background: #555; height: 800px; flex-wrap: wrap; /* 项目在交叉轴对对齐方式(需要设置高度) */ /* align-items: stretch; */ /* 交叉起点对齐 */ align-items: flex-start; /* 交叉终点对齐 */ /* align-items: flex-end; */ /* 以中心点进行对齐 */ /* align-items: center; */ /* 按照第一行文字顶部进行对齐 */ /* align-items: baseline; */ /* 项目在主轴的对齐方式 */ /* 左对齐 */ /* justify-content: flex-start; */ /* 右对齐 */ /* justify-content: flex-end; */ /* 居中对齐 */ /* justify-content: center; */ /* 两端对齐 */ /* justify-content: space-around; */ /* 项目与项目之间的距离相等 */ /* justify-content: space-between; */ /* 项目之间的空隙数相等的 */ /* justify-content: space-evenly; */ /* 起点对齐 */ /* align-content: flex-start; */ /* 终点对齐 */ /* align-content: flex-end; */ /* 终点对齐 */ /* align-content: center; */ /* 两个轴线之间的距离是相等的 */ /* align-content: space-around; */ /* 交叉轴的两端进行对齐 */ /* align-content: space-between; */ /* 默认值 */ /* align-content: stretch; */ } .item { background: #f4f4f4; border: #ccc solid 1px; padding: 1rem; text-align: center; margin: 0.75rem; /* width: 300px; */ flex-basis: 200px; /* 对齐属性 */ } /* 指定设置 */ .item-2 { /* 对单个 item 进行操作 */ align-self: center; /* auto (默认值) flex-start flex-end center baseline stretch */ order: 2; } .item-1 { /* order 可以更改 item 的排列属性 order的值越小他的值就越靠前(默认为0) */ order: 3; } .item-3 { order: 1; }
这些注释都是方法可以自己尝试一下
3. 常用方法
项目在主轴的对齐方式
左对齐
justify-content: flex-start;
右对齐
justify-content: flex-end;
居中对齐
justify-content: center;
两端对齐
justify-content: space-around;
项目与项目之间的距离相等
justify-content: space-between;
项目之间的空隙数相等的
justify-content: space-evenly;
项目在交叉轴对对齐方式(需要设置高度)
align-items: stretch;
交叉起点对齐
align-items: flex-start;
交叉终点对齐
align-items: flex-end;
以中心点进行对齐
align-items: center;
按照第一行文字顶部进行对齐
align-items: baseline;
两个轴的对齐方式
起点对齐
align-content: flex-start;
终点对齐
align-content: flex-end;
终点对齐
align-content: center;
两个轴线之间的距离是相等的
align-content: space-around;
交叉轴的两端进行对齐
align-content: space-between;
默认值
align-content: stretch;
指定设置 对齐方式
.item {
对单个 item 进行操作
align-self: center;
方法
auto (默认值)
flex-start
flex-end
center
baseline
stretch
}
order 属性
order 可以更改 item 的排列属性 order的值越小他的值就越靠前(默认为0)