使用CSS Flexbox为网站创建布局
CSS Flexbox是一个CSS模块,它为网页定义了一个一维的布局。它可以用来在一行或一列中对齐并定义元素行为。Flexbox真的很简单,但使用起来却很强大。
让我们了解一下Flexbox中的一些术语,并利用它建立一个简单的布局。
简介
CSS布局是一个棘手的过程,开发者倾向于使用Bootstrap或Bulma等框架来获得一个好的布局系统。像这样的框架往往会增加项目的重量,因为它们的尺寸和复杂性很大。内置的CSS Flex模块可以替代这些框架,创建轻量级的响应式网站布局。
让我们来看看Flexbox模块中使用的一些基本术语。
术语
容器
容器是一个占位符或包装器,我们在其中应用flex属性。
显示
.bucket {
display: flex;
}
这里,display: flex属性将父容器定义为具有 "bucket "类的元素。Flex属性可以同时应用于父容器和子容器。
主轴、横轴

Flex有一个双坐标轴系统。水平轴被称为主轴,垂直轴被称为横轴。为了在主轴上进行拉伸,可以使用证明属性。要设置十字轴的对齐方式,可以使用对齐属性。
Flex-direction
flex-direction设置父容器中项目的流动方向。
.bucket1 {
display: flex;
flex-direction: row;
}
.bucket2 {
display: flex;
flex-direction: row-reverse;
}
.bucket3 {
display: flex;
flex-direction: column;
}
.bucket4 {
display: flex;
flex-direction: column-reverse;
}
- 行将使项目从左至右流动。
- 列会使项目从上到下流动。
- row-reverse将使项目从右到左流动。
- column-reverse将使元素从底部->顶部流动。
Flex-wrap
flex-wrap定义了当容器的空间用完时元素的行为。
.bucket1 {
flex-wrap: nowrap;
}
.bucket2 {
flex-wrap: wrap;
}
.bucket3 {
flex-wrap: wrap-reverse;
}
- no-wrap属性表示项目不会溢出到下一行,而会被包裹在同一行中。
- wrap属性表示项目会从上到下包成很多行。
- wrap-reverse属性与wrap类似,但会将项目从下往上包起来。
调整内容
justify-content定义了沿着主轴的位置和排列。我们使用的模式定义了如何分配剩余的额外空间。
.bucket {
justify-content: flex-start | flex-end | center;
}
注意--justify-content中还有许多其他模式,但我们看的是基本模式,以理解flexbox的理念。
- flex-start根据flex-direction将项目打包到行/列的开始位置。
- flex-end根据flex-direction将项目打包到行/列的末端。
- center将项目打包到主轴的中心。
对齐项目
align-items定义了沿着十字轴的位置和排列。
.bucket {
align-items: flex-start | flex-end | center;
}
注意--align-items中还有许多其他模式,但我们看的是基本模式,以理解flexbox的理念。
- flex-start将项目打包到十字轴的起点。
- flex-end将项目打包到十字轴的末端。
- center将项目打包到十字轴的中心。
我们的代码
我们的目标是生成一个简单的图像网格,如图所示。

让我们从编写标记开始。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css"
/>
<title>Document</title>
</head>
<body>
<div class="container">
<div class="container1">
<div class="img-box">
<img src="https://picsum.photos/300/200" />
</div>
<div class="img-box">
<img src="https://loremflickr.com/300/200" />
</div>
<div class="img-box">
<img src="https://placekitten.com/300/200" />
</div>
</div>
<div class="container2">
<div class="container3">
<div class="img-box">
<img src="http://lorempixel.com/300/200" />
</div>
<div class="img-box">
<img src="https://source.unsplash.com/random/300x200" />
</div>
</div>
<div class="img-box">
<img src="https://source.unsplash.com/random/600x400" />
</div>
</div>
</div>
</body>
</html>
在这里,我们为每一个我们需要的对齐方式都有一个父容器。
容器1和容器2用于创建一个水平的柔性布局,而容器3用于拥有一个垂直布局。我们从互联网的随机图像生成器中获取图像。
让我们来写样式表吧!
.container1 {
margin-top: 10%;
display: flex;
flex-direction: row;
justify-content: center;
}
.container2 {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.container3 {
display: flex;
flex-direction: column;
justify-content: center;
}
.img-box {
padding: 1em;
}
这可以被嵌入到一个样式标签中,也可以作为一个外部文件链接。在这个代码片段中,justify-content 属性定义了沿主轴的对齐方式,align-items 属性定义了沿容器的交叉轴的对齐方式。