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