盒子模型

CSS 教程 · 第 5 章 · 6 次浏览

盒子模型是 CSS 布局的基础。每个元素都是一个"盒子",由四层组成(从内到外):内容(content)、内边距(padding)、边框(border)、外边距(margin)。

四层结构

  • content:内容区域,width/height 默认作用于它;
  • padding:内容与边框之间的内边距,撑大盒子;
  • border:边框;
  • margin:盒子外部的间距,用于元素间的距离。

box-sizing: border-box 让 width/height 包含 padding 和 border,布局时更直观,业界普遍采用。margin 相邻会合并(取较大值),注意这个特性。

代码示例

<style>
.box {
    width: 200px;              /* 内容宽度 */
    padding: 20px;             /* 内边距 */
    border: 2px solid #3b5bdb; /* 边框 */
    margin: 30px auto;         /* 外边距,水平居中 */
    box-sizing: border-box;    /* 宽度包含 padding 和 border */
    text-align: center;
    background: #f0f4ff;
}
</style>
<div class="box">总宽度仍是 200px</div>
<div class="box" style="margin-top:0;">第二个盒子</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
color: #333;文字颜色
background: #fff;背景色 / 背景图
font-size: 16px;字号
font-family: Arial;字体
font-weight: bold;字重(加粗)
margin: 10px;外边距(上右下左)
padding: 10px;内边距
border: 1px solid #ccc;边框:粗细 样式 颜色
border-radius: 8px;圆角
width: 100%;宽度
height: 200px;高度
display: flex;弹性布局(现代布局主力)
display: none;隐藏元素
position: relative / absolute / fixed;定位方式
top / left / right / bottom定位偏移
text-align: center;文字水平对齐
line-height: 1.6;行高
overflow: hidden;内容溢出处理
box-shadow: 0 2px 8px rgba(0,0,0,.1);阴影
transition: all .3s;过渡动画
cursor: pointer;鼠标手型
z-index: 10;层叠顺序
max-width: 1200px; margin: 0 auto;容器居中(经典写法)
@media (max-width: 768px) {}响应式断点
:hover鼠标悬停状态