CSS弹性盒子详细说明以及案例
参考资料
CSS弹性盒子详细说明以及案例
CSS 弹性盒子(Flexbox)
弹性盒子(Flexbox)是一种用于页面布局的CSS模块,旨在提供一种更高效的方式来对齐、分布和排列容器内的项目,尤其是当项目尺寸未知或动态变化时。
主要概念
容器(Flex Container):
使用
display: flex;或display: inline-flex;来定义一个弹性盒子容器。容器内的子元素成为弹性项目(Flex Items)。
主轴(Main Axis)与交叉轴(Cross Axis):
主轴是弹性项目的主要排列方向,由
flex-direction属性决定。交叉轴是与主轴垂直的轴。
常用容器属性:
flex-direction:定义主轴方向(row,row-reverse,column,column-reverse)。justify-content:定义项目在主轴上的对齐方式(flex-start,flex-end,center,space-between,space-around,space-evenly)。align-items:定义项目在交叉轴上的对齐方式(flex-start,flex-end,center,baseline,stretch)。align-content:定义多行项目在交叉轴上的对齐方式(flex-start,flex-end,center,space-between,space-around,stretch)。flex-wrap:定义项目是否换行(nowrap,wrap,wrap-reverse)。常用项目属性:
order:定义项目的排列顺序。flex-grow:定义项目的放大比例。flex-shrink:定义项目的缩小比例。flex-basis:定义项目在分配多余空间之前的初始大小。align-self:定义单个项目在交叉轴上的对齐方式(auto,flex-start,flex-end,center,baseline,stretch)。
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Example</title>
<style>
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
height: 200px;
border: 2px solid #ccc;
}
.item {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
.item1 {
order: 2;
align-self: flex-start;
}
.item2 {
order: 1;
flex-grow: 2;
}
.item3 {
order: 3;
flex-shrink: 2;
}
</style>
</head>
<body>
<div class="container">
<div class="item item1">1</div>
<div class="item item2">2</div>
<div class="item item3">3</div>
</div>
</body>
</html>解释
容器:
.container使用display: flex;,使其成为一个弹性盒子容器。flex-direction: row;设置主轴为水平方向,justify-content: space-between;使项目在主轴上均匀分布,align-items: center;使项目在交叉轴上居中对齐。项目:
.item是弹性项目,.item1使用order: 2;使其排列在第二个位置,align-self: flex-start;使其在交叉轴上顶部对齐。.item2使用flex-grow: 2;使其在主轴上占据更多空间。.item3使用flex-shrink: 2;使其在主轴上缩小更多。
这个案例展示了如何使用CSS Flexbox进行灵活、响应式的布局设计。

