Skip to content

CSS 语法基础

说明

回顾 CSS 的核心概念和基础语法,巩固扎实的基础。

盒模型 (Box Model)

CSS 盒模型本质上是一个盒子,封装周围的 HTML 元素。它包括:边距(Margin)、边框(Border)、填充(Padding)和实际内容(Content)。

标准盒模型 vs 怪异盒模型

css
/* 标准盒模型 (content-box) - 默认 */
/* width = content */
.box-standard {
  box-sizing: content-box;
}

/* 怪异盒模型 (border-box) - 推荐 */
/* width = content + padding + border */
.box-border {
  box-sizing: border-box;
}

最佳实践

在项目初始化时,建议将所有元素设置为 border-box,以便更好地控制布局。

css
*,
*::before,
*::after {
  box-sizing: border-box;
}

选择器与优先级

CSS 选择器的优先级(权重)决定了哪条规则生效。

选择器示例权重
!importantcolor: red !importantInfinity
行内样式style="..."1000
ID 选择器#header100
类、伪类、属性.btn, :hover, [type="text"]10
标签、伪元素div, ::before1
通配符*0

定位 (Position)

属性值描述参考点
static默认值文档流
relative相对定位自身原本的位置
absolute绝对定位最近的非 static 祖先元素
fixed固定定位浏览器窗口 (Viewport)
sticky粘性定位滚动容器 (基于阈值切换 relative/fixed)

布局 (Layout)

Flexbox 常用属性

css
.container {
  display: flex;

  /* 主轴方向 */
  flex-direction: row | column;

  /* 换行 */
  flex-wrap: nowrap | wrap;

  /* 主轴对齐 */
  justify-content: flex-start | center | flex-end | space-between | space-around;

  /* 交叉轴对齐 */
  align-items: flex-start | center | flex-end | stretch;
}

Grid 常用属性

css
.container {
  display: grid;

  /* 定义列 */
  grid-template-columns: repeat(3, 1fr); /* 3列等宽 */

  /* 定义行 */
  grid-template-rows: auto;

  /* 间距 */
  gap: 20px;
}

如有转载或 CV 的请标注本站原文地址