10.1 简单网格
Flexbox 让创建灵活且自适应的布局变得简单。现在我们来看几个使用 Flexbox 创建不同布局的例子,包括简单网格、元素居中、创建导航菜单和商品卡片。
使用 Flexbox 创建简单网格的例子。这个例子展示了如何轻松在容器中创建均匀分布的元素。
使用示例:
CSS
.flex-container {
display: flex;
flex-wrap: wrap; /* 让元素换行 */
background-color: lightgrey;
padding: 10px;
}
.flex-item {
background-color: deepskyblue;
margin: 10px;
padding: 20px;
color: white;
font-size: 20px;
flex: 1 1 calc(33.333% - 40px); /* 灵活的空间分配 */
box-sizing: border-box;
}
HTML
<div class="flex-container">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
<div class="flex-item">Item 4</div>
<div class="flex-item">Item 5</div>
<div class="flex-item">Item 6</div>
</div>
flex-basis: calc(33.333% - 40px):
确定元素的初始大小,然后再应用任何拉伸或压缩。在这种情况下,元素将占据容器宽度的 33.333%,减去 40 像素。calc()
允许你在 CSS 中直接进行计算。
10.2 元素居中
使用 Flexbox 将元素在容器中水平和垂直居中。
使用示例:
CSS
.flex-container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 容器高度占满整个视口 */
background-color: lightgrey;
}
.flex-item {
background-color: deepskyblue;
padding: 20px;
color: white;
font-size: 20px;
}
HTML
<div class="flex-container">
<div class="flex-item">Centered Item</div>
</div>
10.3 导航菜单
使用 Flexbox 创建水平导航菜单。
使用示例:
CSS
.nav-container {
display: flex;
justify-content: space-around; /* 元素间等距分布 */
background-color: #333;
padding: 10px;
}
.nav-item {
color: white;
text-decoration: none;
padding: 10px 20px;
}
.nav-item:hover {
background-color: #575757;
}
HTML
<div class="nav-container">
<a href="#" class="nav-item">Home</a>
<a href="#" class="nav-item">About</a>
<a href="#" class="nav-item">Services</a>
<a href="#" class="nav-item">Contact</a>
</div>
10.4 商品卡片
使用 Flexbox 创建商品卡片布局。
使用示例:
CSS
.product-list {
display: flex;
flex-wrap: wrap;
gap: 20px;
padding: 20px;
}
.product-item {
flex: 1 1 calc(33.333% - 40px);
border: 1px solid #ccc;
padding: 20px;
background-color: #fff;
text-align: center;
}
.product-item img {
max-width: 100%;
height: auto;
}
.product-title {
font-size: 1.2em;
margin: 10px 0;
}
.product-price {
font-size: 1.5em;
color: #e74c3c;
}
HTML
<div class="product-list">
<div class="product-item">
<img src="https://via.placeholder.com/150" alt="Product Image">
<h3 class="product-title">商品 1</h3>
<p class="product-price">$99.99</p>
</div>
<div class="product-item">
<img src="https://via.placeholder.com/150" alt="Product Image">
<h3 class="product-title">商品 2</h3>
<p class="product-price">$79.99</p>
</div>
<div class="product-item">
<img src="https://via.placeholder.com/150" alt="Product Image">
<h3 class="product-title">商品 3</h3>
<p class="product-price">$89.99</p>
</div>
</div>
代码解释:
.product-list
: 支持换行的 Flex 容器,商品卡片间有间距.product-item
: 固定宽度且自动适应容器大小的 Flex 元素(商品卡片)
GO TO FULL VERSION