类选择器与盒模型是专业排版的分水岭 | 课型:实习课 | 建议课时:2节
拖动滑块实时调整padding/border/margin,直观看到盒模型变化与总尺寸计算。
新窗口运行 下载源码<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>盒模型互动实验室</title>
<style>
body { font-family: "Microsoft YaHei", sans-serif; max-width: 720px; margin: 30px auto; padding: 0 16px; color: #1f2a33; }
.lab { display: flex; gap: 30px; align-items: center; flex-wrap: wrap; }
.margin-area { background: #fdeeda; padding: var(--m, 20px); }
.border-area { background: #e7f7f4; border: var(--b, 4px) solid #0f8c7f; padding: var(--p, 20px); }
.content { background: #123a52; color: #fff; width: 160px; height: 80px;
display: flex; align-items: center; justify-content: center; }
label { display: block; margin: 12px 0; }
output { font-weight: bold; color: #c77728; }
#result { background: #f2f6f8; padding: 12px; border-radius: 8px; margin-top: 16px; }
</style>
</head>
<body>
<h1>盒模型互动实验室</h1>
<div class="lab">
<div class="margin-area" title="margin">
<div class="border-area" title="border+padding">
<div class="content">content 160×80</div>
</div>
</div>
<div>
<label>padding: <input type="range" id="p" min="0" max="60" value="20"> <output id="pv">20</output>px</label>
<label>border: <input type="range" id="b" min="0" max="20" value="4"> <output id="bv">4</output>px</label>
<label>margin: <input type="range" id="m" min="0" max="60" value="20"> <output id="mv">20</output>px</label>
</div>
</div>
<div id="result"></div>
<script>
const $ = id => document.getElementById(id);
function update() {
const p = +$('p').value, b = +$('b').value, m = +$('m').value;
document.querySelector('.margin-area').style.setProperty('--m', m + 'px');
document.querySelector('.border-area').style.setProperty('--b', b + 'px');
document.querySelector('.border-area').style.setProperty('--p', p + 'px');
$('pv').textContent = p; $('bv').textContent = b; $('mv').textContent = m;
const total = 160 + 2 * (p + b + m);
$('result').textContent = '元素总宽度 = 160 + 2×(' + p + '+' + b + '+' + m + ') = ' + total + ' px(content-box算法)';
}
['p','b','m'].forEach(id => $(id).addEventListener('input', update));
update();
</script>
</body>
</html>任务目标:用外部样式表重写"我的爱好"页面,精确控制间距与视觉细节
| 任务内容与评分 |
|---|
| 任务1:创建style.css并正确link引入(15分) |
| 任务2:用类选择器为三个爱好卡片设置相同样式(20分) |
| 任务3:用盒模型知识使卡片内边距20px、间距24px(25分) |
| 任务4:添加圆角12px与柔和阴影(20分) |
| 任务5:用开发者工具截图一个元素的盒模型图并标注四层(20分) |