当使用 Flex 布局时,我们通常有两个主要的部分:弹性容器(Flex Container)和弹性项目(Flex Items)。
1. 弹性容器(Flex Container)
弹性容器是应用 Flex 布局的父元素。通过设置容器的 display
属性为 flex
或 inline-flex
,我们可以启用 Flex 布局。
1.1 display
属性
.container {
display: flex;
/* 或者使用 inline-flex,取决于布局需求 */
/* display: inline-flex; */
}
1.2 flex-direction
属性
flex-direction
属性决定主轴的方向,有四个可能的值:row
、row-reverse
、column
、column-reverse
。
.container {
flex-direction: row; /* 默认值,水平方向 */
/* flex-direction: row-reverse; 水平方向反向 */
/* flex-direction: column; 垂直方向 */
/* flex-direction: column-reverse; 垂直方向反向 */
}
1.3 justify-content
属性
justify-content
属性定义了沿着主轴的对齐方式。
.container {
justify-content: flex-start; /* 默认值,起点对齐 */
/* justify-content: flex-end; 终点对齐 */
/* justify-content: center; 居中对齐 */
/* justify-content: space-between; 两端对齐,项目之间均匀分布 */
/* justify-content: space-around; 每个项目周围均匀分布 */
/* justify-content: space-evenly; 所有项目均匀分布,包括起点和终点 */
}
1.4 align-items
属性
align-items
属性定义了沿着交叉轴的对齐方式。
.container {
align-items: stretch; /* 默认值,项目被拉伸以适应容器 */
/* align-items: flex-start; 交叉轴起点对齐 */
/* align-items: flex-end; 交叉轴终点对齐 */
/* align-items: center; 交叉轴居中对齐 */
/* align-items: baseline; 项目的基线对齐 */
}
1.5 完整的弹性容器示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
height: 150px; /* 为了演示效果,设置容器高度 */
border: 1px solid #333; /* 为了演示效果,添加边框 */
}
.item {
flex: 1;
text-align: center;
padding: 10px;
border: 1px solid #999; /* 为了演示效果,添加边框 */
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>
这个示例创建了一个水平方向的 Flex 容器,项目之间有空白空间,项目在交叉轴上居中对齐。
2. 弹性项目(Flex Items)
弹性项目是 Flex 布局中的子元素,它们存在于弹性容器内。弹性项目具有灵活的布局属性。
2.1 flex
属性
flex
属性是 flex-grow
、flex-shrink
和 flex-basis
的缩写。
.item {
flex: 1; /* 等同于 flex: 1 1 0; */
/* flex: 0 1 auto; 不放大,允许缩小,基础大小为自动 */
/* flex: 2; 放大为2,允许缩小,基础大小为0 */
}
2.2 align-self
属性
align-self
属性允许单个项目在交叉轴上有不同的对齐方式,覆盖容器的 align-items
属性。
.item {
align-self: flex-start; /* 项目在交叉轴上顶部对齐 */
/* align-self: flex-end; 项目在交叉轴上底部对齐 */
/* align-self: center; 项目在交叉轴上居中对齐 */
}
2.3 完整的弹性项目示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
height: 150px;
border: 1px solid #333;
}
.item {
flex: 1;
text-align: center;
padding: 10px;
border: 1px solid #999;
}
.item:nth-child(2) {
align-self: flex-start; /* 第二个项目在交叉轴上顶部对齐 */
}
</style>
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>
在这个示例中,第二个项目被设置为在交叉轴上顶部对齐,而其他项目仍然保持默认的居中对
齐。