理解 CSS 盒模型,掌握背景和边框的高级用法
.box-model-demo {
width: 300px;
height: 200px;
background: #3498db;
border: 5px solid #2c3e50;
padding: 20px;
margin: 20px;
}默认情况下,CSS 的 width 和 height 属性只包括内容区域的尺寸,不包括 padding 和 border。这意味着当你设置 width: 100px 时,实际的元素宽度会是 100px + padding + border,这会导致布局计算变得复杂。
| 属性 | content-box(默认) | border-box |
|---|---|---|
| width 计算 | 仅内容区域 | 内容 + padding + border |
| 布局计算 | 复杂,需要考虑 padding 和 border | 简单,width 就是最终宽度 |
| 响应式设计 | 容易出错 | 更可靠 |
/* 全局设置 box-sizing: border-box */
*,
*::before,
*::after {
box-sizing: border-box;
}当两个垂直相邻的元素都有外边距时,它们的外边距会折叠成一个,取较大的值。
.box1 {
margin-bottom: 30px;
}
.box2 {
margin-top: 20px;
}
/* 实际间距:30px(取较大值)*/.hero {
background-image: url('hero.jpg');
background-position: center;
background-size: cover;
background-repeat: no-repeat;
height: 100vh;
}.multiple-backgrounds {
background:
linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
url('background.jpg') center/cover no-repeat;
}/* 线性渐变 */
.linear-gradient {
background: linear-gradient(to right, #3498db, #2ecc71);
}
/* 径向渐变 */
.radial-gradient {
background: radial-gradient(circle, #3498db, #2ecc71);
}
/* 锥形渐变 */
.conic-gradient {
background: conic-gradient(#3498db, #2ecc71, #3498db);
}.rounded {
border-radius: 8px;
}
.circle {
border-radius: 50%;
}
.pill {
border-radius: 50px;
}
.custom-rounded {
border-radius: 10px 20px 30px 40px;
}.card {
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.card-hover {
box-shadow: 0 10px 20px rgba(0,0,0,0.2);
transition: box-shadow 0.3s ease;
}
.card-hover:hover {
box-shadow: 0 15px 30px rgba(0,0,0,0.3);
}
.inner-shadow {
box-shadow: inset 0 0 10px rgba(0,0,0,0.2);
}.focused {
outline: 2px solid #3498db;
outline-offset: 4px;
}