一维布局的终极武器 | 课型:实习课 | 建议课时:2节
下拉选择不同的flex-direction/justify-content/align-items,九个方块实时重排。
新窗口运行 下载源码<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Flex演练场</title>
<style>
body { font-family: "Microsoft YaHei", sans-serif; max-width: 780px; margin: 24px auto; padding: 0 16px; color: #1f2a33; }
.controls { display: flex; gap: 16px; flex-wrap: wrap; margin-bottom: 16px; }
label { font-size: 14px; }
select { padding: 6px 10px; border-radius: 6px; border: 1px solid #6b8a99; }
#box { display: flex; gap: 8px; background: #f2f6f8; border: 2px dashed #0f8c7f;
border-radius: 10px; padding: 10px; height: 220px; }
.item { background: linear-gradient(135deg, #123a52, #1b5a7a); color: #38d6c4;
border-radius: 8px; width: 56px; height: 56px; display: flex;
align-items: center; justify-content: center; font-weight: bold; }
.item:nth-child(2n) { height: 80px; }
#code { background: #123a52; color: #38d6c4; padding: 12px 16px; border-radius: 8px;
font-family: Consolas, monospace; margin-top: 14px; white-space: pre; }
</style>
</head>
<body>
<h1>Flex演练场</h1>
<div class="controls">
<label>flex-direction <select id="d">
<option>row</option><option>row-reverse</option><option>column</option><option>column-reverse</option>
</select></label>
<label>justify-content <select id="j">
<option>flex-start</option><option>center</option><option>flex-end</option>
<option>space-between</option><option>space-around</option><option>space-evenly</option>
</select></label>
<label>align-items <select id="a">
<option>stretch</option><option>flex-start</option><option>center</option><option>flex-end</option>
</select></label>
</div>
<div id="box"></div>
<div id="code"></div>
<script>
const box = document.getElementById('box');
for (let i = 1; i <= 9; i++) {
const d = document.createElement('div');
d.className = 'item'; d.textContent = i; box.appendChild(d);
}
const $ = id => document.getElementById(id);
function apply() {
box.style.flexDirection = $('d').value;
box.style.justifyContent = $('j').value;
box.style.alignItems = $('a').value;
$('code').textContent = '#box {
display: flex;
flex-direction: ' + $('d').value +
';
justify-content: ' + $('j').value + ';
align-items: ' + $('a').value + ';
}';
}
['d','j','a'].forEach(id => $(id).addEventListener('change', apply));
apply();
</script>
</body>
</html>任务目标:用Flexbox独立完成照片墙与经典居中布局
| 任务内容与评分 |
|---|
| 任务1:制作水平垂直居中的登录卡片(25分) |
| 任务2:制作flex-wrap自动换行的照片墙(6张占位图)(30分) |
| 任务3:制作"logo左-导航右"的贴边导航栏(20分) |
| 任务4:用flex:1制作三等分功能区(15分) |
| 任务5:写出align-items与align-content的区别(10分) |