Skip to content

CSS 样式属性全面指南:从基础到架构

一、CSS 基础概述

1.1 什么是 CSS

CSS(Cascading Style Sheets,层叠样式表)是一种用于描述 HTML 或 XML 文档外观和格式的标记语言。它允许开发者将文档的结构(HTML)与表现(CSS)分离,使网页的设计更加灵活和易于维护。

CSS 的主要作用:

  • 控制网页的布局和排版
  • 定义文本样式(字体、颜色、大小等)
  • 设置背景和边框效果
  • 创建动画和过渡效果
  • 实现响应式设计,适应不同设备

CSS 的三种引入方式:

内联样式:直接在 HTML 元素中使用 style 属性

html
<p style="color: red;">红色文本</p>

内部样式表:在 HTML 文档的<head>部分使用<style>标签

html
<head>
  <style>
    p {
      color: red;
    }
  </style>
</head>

外部样式表:通过<link>标签引用外部 CSS 文件

html
<link rel="stylesheet" type="text/css" href="styles.css" />

1.2 CSS 语法基础

CSS 规则基本结构:

css
selector {
  property1: value1;
  property2: value2;
  property3: value3;
}
  • 选择器(selector):指定要应用样式的 HTML 元素
  • 属性(property):要设置的样式属性
  • 值(value):属性的具体取值
  • 注释
css
/* 这是CSS注释,不会被浏览器解析 */

继承性:某些 CSS 属性会自动继承父元素的值,如colorfont-family等。可以通过inherit关键字强制继承:

css
span {
  color: inherit; /* 继承父元素的颜色 */
}

层叠性:当多个样式规则应用于同一元素时,浏览器会根据优先级规则决定最终应用哪个样式。优先级由高到低依次为:

  • 内联样式(最高优先级)
  • ID 选择器
  • 类选择器、属性选择器、伪类
  • 元素选择器(最低优先级)

二、文本与字体属性

2.1 字体控制属性

  • font-family:指定字体列表,浏览器按顺序查找可用字体
css
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
  • font-size:设置字体大小,支持多种单位(px、em、rem、% 等)
css
h1 {
  font-size: 24px; /* 绝对大小 */
}

p {
  font-size: 1.2em; /* 相对于父元素的字体大小 */
}
  • font-weight:设置字体粗细
css
.normal {
  font-weight: normal; /* 400 */
}

.bold {
  font-weight: bold; /* 700 */
}

.light {
  font-weight: 300; /* 具体数值 */
}
  • font-style:设置字体样式
css
.italic {
  font-style: italic; /* 斜体 */
}

.oblique {
  font-style: oblique; /* 倾斜 */
}

.normal {
  font-style: normal; /* 正常 */
}
  • font-variant:设置小型大写字母
css
.small-caps {
  font-variant: small-caps;
}
  • font:复合属性,可以同时设置多个字体属性
css
/* 语法:font: [font-style] [font-variant] [font-weight] [font-size]/[line-height] [font-family] */
body {
  font: italic small-caps bold 16px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

2.2 文本样式属性

  • color:设置文本颜色,支持多种颜色表示方式
css
p {
  color: #ff0000; /* 十六进制 */
  color: rgb(255, 0, 0); /* RGB值 */
  color: rgba(255, 0, 0, 0.5); /* 带有透明度的RGB */
  color: hsl(0, 100%, 50%); /* HSL值 */
  color: hsla(0, 100%, 50%, 0.5); /* 带有透明度的HSL */
  color: red; /* 颜色名称 */
}
  • text-align:设置文本水平对齐方式
css
.left {
  text-align: left; /* 左对齐(默认) */
}

.center {
  text-align: center; /* 居中对齐 */
}

.right {
  text-align: right; /* 右对齐 */
}

.justify {
  text-align: justify; /* 两端对齐 */
}
  • text-decoration:设置文本装饰线
css
.underline {
  text-decoration: underline; /* 下划线 */
}

.line-through {
  text-decoration: line-through; /* 中划线 */
}

.overline {
  text-decoration: overline; /* 上划线 */
}

.none {
  text-decoration: none; /* 无装饰(常用于移除链接的下划线) */
}
  • text-indent:设置首行缩进
css
p {
  text-indent: 2em; /* 首行缩进两个字符宽度 */
}
  • text-transform:设置文本大小写转换
css
.uppercase {
  text-transform: uppercase; /* 全部大写 */
}

.lowercase {
  text-transform: lowercase; /* 全部小写 */
}

.capitalize {
  text-transform: capitalize; /* 每个单词首字母大写 */
}
  • letter-spacing:设置字符间距
css
.letter-spacing-normal {
  letter-spacing: normal; /* 默认值 */
}

.letter-spacing-wide {
  letter-spacing: 2px; /* 增加字符间距 */
}

.letter-spacing-narrow {
  letter-spacing: -0.5px; /* 减少字符间距 */
}
  • word-spacing:设置单词间距(仅适用于英文)
css
.word-spacing-normal {
  word-spacing: normal; /* 默认值 */
}

.word-spacing-wide {
  word-spacing: 4px; /* 增加单词间距 */
}
  • line-height:设置行高
css
.single-line {
  line-height: 1; /* 单倍行距 */
}

.double-line {
  line-height: 2; /* 双倍行距 */
}

.px-line {
  line-height: 24px; /* 固定行高 */
}
  • white-space:控制空白符处理方式
css
.normal {
  white-space: normal; /* 默认值,合并空白符,自动换行 */
}

.nowrap {
  white-space: nowrap; /* 不换行 */
}

.pre {
  white-space: pre; /* 保留空白符,不自动换行,类似<pre>标签 */
}

.pre-line {
  white-space: pre-line; /* 保留换行符,合并其他空白符 */
}

.pre-wrap {
  white-space: pre-wrap; /* 保留空白符和换行符,自动换行 */
}
  • text-shadow:添加文本阴影
css
.shadow {
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); /* 水平偏移、垂直偏移、模糊半径、颜色 */
}
  • text-overflow:设置文本溢出处理方式
css
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis; /* 溢出时显示省略号 */
}

.clip {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip; /* 直接裁剪溢出内容 */
}

三、盒模型与布局属性

3.1 盒模型基础

CSS 盒模型是 CSS 布局的基础,每个 HTML 元素都被视为一个矩形盒子,由以下部分组成:

  • 内容区(content):元素的实际内容

  • 内边距(padding):内容区与边框之间的区域

  • 边框(border):围绕内边距和内容的线条

  • 外边距(margin):元素与其他元素之间的区域

  • box-sizing:控制盒模型的计算方式

css
.content-box {
  box-sizing: content-box; /* 默认值,width和height仅包含内容区 */
}

.border-box {
  box-sizing: border-box; /* width和height包含内容区、内边距和边框 */
}

3.2 尺寸与边距属性

  • width 和 height:设置元素的宽度和高度
css
.box {
  width: 200px; /* 固定宽度 */
  height: 150px; /* 固定高度 */
  max-width: 100%; /* 最大宽度不超过父元素的100% */
  min-height: 100px; /* 最小高度 */
}
  • padding:设置内边距
css
/* 单值:同时设置四个方向的内边距 */
.box {
  padding: 20px;
}

/* 双值:上下、左右 */
.box {
  padding: 20px 40px;
}

/* 三值:上、左右、下 */
.box {
  padding: 20px 40px 30px;
}

/* 四值:上、右、下、左(顺时针顺序) */
.box {
  padding: 20px 40px 30px 50px;
}

/* 单独设置每个方向的内边距 */
.box {
  padding-top: 20px;
  padding-right: 40px;
  padding-bottom: 30px;
  padding-left: 50px;
}
  • margin:设置外边距
css
/* 与padding语法相同 */
.box {
  margin: 20px;
}

/* 自动水平居中 */
.center {
  margin: 0 auto;
}
  • border:设置边框
css
/* 复合属性:width style color */
.box {
  border: 2px solid #333;
}

/* 单独设置每个方向的边框 */
.box {
  border-top: 2px solid #333;
  border-right: 1px dashed #666;
  border-bottom: 2px solid #333;
  border-left: 1px dashed #666;
}

/* 边框半径 */
.rounded {
  border-radius: 10px; /* 圆角 */
  border-radius: 50%; /* 圆形 */
}

3.3 显示与隐藏属性

  • display:设置元素的显示类型
css
.block {
  display: block; /* 块级元素,独占一行 */
}

.inline {
  display: inline; /* 行内元素,不独占一行 */
}

.inline-block {
  display: inline-block; /* 行内块元素,不独占一行但可以设置宽高 */
}

.none {
  display: none; /* 元素完全隐藏,不占用空间 */
}

.table {
  display: table; /* 表格布局 */
}

.table-row {
  display: table-row;
}

.table-cell {
  display: table-cell;
}
  • visibility:设置元素的可见性
css
.visible {
  visibility: visible; /* 可见(默认值) */
}

.hidden {
  visibility: hidden; /* 隐藏,但仍占用空间 */
}

.collapse {
  visibility: collapse; /* 用于表格,隐藏行或列 */
}

3.4 定位与浮动属性

  • position:设置元素的定位方式
css
.static {
  position: static; /* 默认值,正常文档流 */
}

.relative {
  position: relative; /* 相对定位,相对于自身原来的位置 */
  top: 20px;
  left: 10px;
}

.absolute {
  position: absolute; /* 绝对定位,相对于最近的已定位祖先元素 */
  top: 50px;
  right: 0;
}

.fixed {
  position: fixed; /* 固定定位,相对于视口 */
  bottom: 0;
  left: 0;
}

.sticky {
  position: sticky; /* 粘性定位,根据滚动位置自动切换相对定位和固定定位 */
  top: 20px;
}
  • float:设置元素浮动
css
.left {
  float: left; /* 向左浮动 */
}

.right {
  float: right; /* 向右浮动 */
}

.none {
  float: none; /* 不浮动(默认值) */
}
  • clear:清除浮动
css
.clear {
  clear: both; /* 清除左右两侧的浮动 */
}

3.5 溢出与裁剪属性

  • overflow:设置内容溢出时的处理方式
css
.visible {
  overflow: visible; /* 默认值,内容溢出时可见 */
}

.hidden {
  overflow: hidden; /* 隐藏溢出内容 */
}

.scroll {
  overflow: scroll; /* 总是显示滚动条 */
}

.auto {
  overflow: auto; /* 内容溢出时显示滚动条,否则不显示 */
}
  • clip:设置元素内容的裁剪区域(已过时,建议使用 clip-path)
css
.clip {
  position: absolute;
  clip: rect(0 200px 150px 0); /* 上右下左 */
}
  • clip-path:设置元素的裁剪路径
css
.circle {
  clip-path: circle(50%); /* 圆形裁剪 */
}

.polygon {
  clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); /* 矩形裁剪 */
}

四、背景与颜色属性

4.1 背景属性

  • background-color:设置背景颜色
css
body {
  background-color: #f0f0f0; /* 十六进制颜色 */
  background-color: rgba(255, 0, 0, 0.5); /* 透明红色 */
}
  • background-image:设置背景图像
css
.box {
  background-image: url("image.jpg"); /* 单张背景图片 */
  background-image: linear-gradient(to bottom, #ff0000, #00ff00); /* 线性渐变 */
  background-image: radial-gradient(circle, #ff0000, #00ff00); /* 径向渐变 */
}
  • background-repeat:设置背景图像的重复方式
css
.repeat {
  background-repeat: repeat; /* 默认值,在水平和垂直方向重复 */
}

.repeat-x {
  background-repeat: repeat-x; /* 仅水平方向重复 */
}

.repeat-y {
  background-repeat: repeat-y; /* 仅垂直方向重复 */
}

.no-repeat {
  background-repeat: no-repeat; /* 不重复 */
}
  • background-position:设置背景图像的位置
css
.center {
  background-position: center; /* 居中 */
}

.top-right {
  background-position: top right; /* 右上 */
}

.pixel {
  background-position: 20px 30px; /* 相对于左上角的偏移量 */
}

.percent {
  background-position: 50% 50%; /* 百分比定位 */
}
  • background-size:设置背景图像的尺寸
css
.cover {
  background-size: cover; /* 覆盖整个容器,可能裁剪 */
}

.contain {
  background-size: contain; /* 包含在容器内,可能留有空白 */
}

.pixel {
  background-size: 200px 150px; /* 固定尺寸 */
}

.percent {
  background-size: 100% 50%; /* 百分比尺寸 */
}
  • background-attachment:设置背景图像是否随滚动条移动
css
.scroll {
  background-attachment: scroll; /* 默认值,背景图像随内容滚动 */
}

.fixed {
  background-attachment: fixed; /* 背景图像固定在视口 */
}

.local {
  background-attachment: local; /* 背景图像随元素内容滚动 */
}
  • background:复合属性,可以同时设置多个背景属性
css
/* 语法**:background: [color] [image] [repeat] [position] [size] [attachment] */
.box {
  background: #f0f0f0 url("image.jpg") no-repeat center/cover fixed;
}

4.2 颜色相关属性

  • opacity:设置元素的整体透明度
css
.box {
  opacity: 0.5; /* 完全透明到完全不透明(0到1之间的值) */
}
  • filter:设置图像滤镜效果
css
.blur {
  filter: blur(5px); /* 模糊效果 */
}

.brightness {
  filter: brightness(1.5); /* 亮度调整 */
}

.contrast {
  filter: contrast(120%); /* 对比度调整 */
}

.grayscale {
  filter: grayscale(100%); /* 灰度化 */
}

.hue-rotate {
  filter: hue-rotate(90deg); /* 色相旋转 */
}

.invert {
  filter: invert(100%); /* 反相 */
}

.saturate {
  filter: saturate(200%); /* 饱和度调整 */
}

.sepia {
  filter: sepia(100%); /* 褐色调 */
}

.drop-shadow {
  filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.5)); /* 投影效果 */
}
  • mix-blend-mode:设置元素与背景的混合模式
css
.overlay {
  mix-blend-mode: overlay; /* 叠加模式 */
}

.multiply {
  mix-blend-mode: multiply; /* 正片叠底模式 */
}

.screen {
  mix-blend-mode: screen; /* 滤色模式 */
}

五、列表与表格属性

5.1 列表属性

  • list-style-type:设置列表项的标记类型
css
ul {
  list-style-type: disc; /* 默认值,实心圆 */
  list-style-type: circle; /* 空心圆 */
  list-style-type: square; /* 实心方块 */
  list-style-type: decimal; /* 阿拉伯数字 */
  list-style-type: lower-roman; /* 小写罗马数字 */
  list-style-type: upper-roman; /* 大写罗马数字 */
  list-style-type: lower-alpha; /* 小写英文字母 */
  list-style-type: upper-alpha; /* 大写英文字母 */
  list-style-type: none; /* 无标记 */
}
  • list-style-image:设置列表项的自定义图像标记
css
ul {
  list-style-image: url("bullet.png");
}
  • list-style-position:设置列表项标记的位置
css
ul {
  list-style-position: outside; /* 默认值,标记在列表项外部 */
  list-style-position: inside; /* 标记在列表项内部 */
}
  • list-style:复合属性,可以同时设置多个列表属性
css
ul {
  list-style: square inside url("bullet.png");
}

5.2 表格属性

  • border-collapse:设置表格边框是否合并
css
table {
  border-collapse: collapse; /* 边框合并 */
  border-collapse: separate; /* 边框分离(默认值) */
}
  • border-spacing:设置分离边框表格的单元格边框间距
css
table {
  border-spacing: 5px; /* 水平和垂直间距 */
  border-spacing: 5px 10px; /* 水平和垂直间距(先水平后垂直) */
}
  • caption-side:设置表格标题的位置
css
table {
  caption-side: top; /* 默认值,标题在表格上方 */
  caption-side: bottom; /* 标题在表格下方 */
}
  • empty-cells:设置是否显示空单元格的边框和背景
css
table {
  empty-cells: show; /* 默认值,显示空单元格 */
  empty-cells: hide; /* 隐藏空单元格 */
}
  • table-layout:设置表格的布局算法
css
table {
  table-layout: auto; /* 默认值,根据内容自动调整列宽 */
  table-layout: fixed; /* 固定布局,列宽由表格宽度和列宽属性决定 */
}

六、用户界面与交互属性

6.1 鼠标与光标属性

  • cursor:设置鼠标光标样式
css
.pointer {
  cursor: pointer; /* 手型光标,用于可点击元素 */
}

.help {
  cursor: help; /* 帮助光标 */
}

.wait {
  cursor: wait; /* 等待光标 */
}

.text {
  cursor: text; /* 文本选择光标 */
}

.not-allowed {
  cursor: not-allowed; /* 禁止光标 */
}

.move {
  cursor: move; /* 移动光标 */
}

.custom {
  cursor: url("custom.cur"), auto; /* 自定义光标 */
}

6.2 滚动条属性

  • scrollbar-width:设置滚动条的宽度
css
.scrollable {
  scrollbar-width: thin; /* 细滚动条 */
  scrollbar-width: auto; /* 默认宽度 */
  scrollbar-width: none; /* 隐藏滚动条,但仍可滚动 */
}
  • scrollbar-color:设置滚动条的颜色
css
.scrollable {
  scrollbar-color: #666 #f0f0f0; /* 滑块颜色 轨道颜色 */
}
  • scrollbar-gutter:设置是否为滚动条预留空间
css
.scrollable {
  scrollbar-gutter: stable; /* 预留空间 */
  scrollbar-gutter: stable both-edges; /* 两侧都预留空间 */
}

6.3 选择与聚焦属性

  • ::selection:设置选中文本的样式
css
::selection {
  background-color: #ff0000; /* 背景颜色 */
  color: #ffffff; /* 文本颜色 */
}
  • outline:设置元素获得焦点时的轮廓
css
:focus {
  outline: none; /* 移除默认焦点轮廓 */
  outline: 2px solid #333; /* 自定义焦点轮廓 */
}
  • resize:设置元素是否可调整大小
css
.resizeable {
  resize: both; /* 可调整宽度和高度 */
  resize: horizontal; /* 仅可调整宽度 */
  resize: vertical; /* 仅可调整高度 */
  resize: none; /* 不可调整大小(默认值) */
}

七、动画与过渡属性

7.1 过渡属性

  • transition:设置元素属性变化的过渡效果
css
/* 语法**:transition: [property] [duration] [timing-function] [delay] */
.box {
  transition: all 0.3s ease-in-out 0.1s;
}

/* 单独设置每个属性 */
.box {
  transition-property: background-color, transform; /* 要过渡的属性 */
  transition-duration: 0.3s; /* 过渡持续时间 */
  transition-timing-function: ease-in-out; /* 过渡时间函数 */
  transition-delay: 0.1s; /* 过渡延迟时间 */
}
  • transition-timing-function:设置过渡的时间函数
css
.linear {
  transition-timing-function: linear; /* 匀速 */
}

.ease {
  transition-timing-function: ease; /* 默认值,慢-快-慢 */
}

.ease-in {
  transition-timing-function: ease-in; /* 慢入 */
}

.ease-out {
  transition-timing-function: ease-out; /* 慢出 */
}

.ease-in-out {
  transition-timing-function: ease-in-out; /* 慢入慢出 */
}

.cubic-bezier {
  transition-timing-function: cubic-bezier(
    0.42,
    0,
    0.58,
    1
  ); /* 自定义贝塞尔曲线 */
}

7.2 动画属性

  • @keyframes:定义动画的关键帧
css
@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes slideIn {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}
  • animation:应用动画并设置属性
css
/* 语法**:animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction] [fill-mode] [play-state] */
.box {
  animation: fadeIn 0.5s ease-in-out 0s 1 normal forwards running;
}

/* 单独设置每个属性 */
.box {
  animation-name: fadeIn; /* 动画名称 */
  animation-duration: 0.5s; /* 动画持续时间 */
  animation-timing-function: ease-in-out; /* 动画时间函数 */
  animation-delay: 0s; /* 动画延迟时间 */
  animation-iteration-count: 1; /* 动画循环次数(infinite表示无限循环) */
  animation-direction: normal; /* 动画方向 */
  animation-fill-mode: forwards; /* 动画结束后的状态 */
  animation-play-state: running; /* 动画播放状态(paused表示暂停) */
}
  • animation-iteration-count:设置动画的循环次数
css
.box {
  animation-iteration-count: 3; /* 播放3次 */
  animation-iteration-count: infinite; /* 无限循环 */
}
  • animation-direction:设置动画的播放方向
css
.box {
  animation-direction: normal; /* 默认值,正向播放 */
  animation-direction: reverse; /* 反向播放 */
  animation-direction: alternate; /* 交替播放(正-反-正...) */
  animation-direction: alternate-reverse; /* 交替反向播放(反-正-反...) */
}
  • animation-fill-mode:设置动画结束后的状态
css
.box {
  animation-fill-mode: none; /* 默认值,动画结束后回到初始状态 */
  animation-fill-mode: forwards; /* 动画结束后保持最后一帧的状态 */
  animation-fill-mode: backwards; /* 动画开始前应用第一帧的状态 */
  animation-fill-mode: both; /* 同时应用forwards和backwards */
}

八、高级布局技术

8.1 Flexbox 布局

Flexbox(弹性盒模型)是 CSS3 中引入的一种一维布局模型,用于在容器中排列和分配子元素的空间。

基本概念:

  • 容器(flex container):设置display: flexdisplay: inline-flex的元素
  • 项目(flex item):容器的直接子元素
  • 主轴(main axis):元素排列的主要方向
  • 交叉轴(cross axis):与主轴垂直的方向

容器属性:

css
.container {
  display: flex; /* 块级弹性容器 */
  display: inline-flex; /* 行内弹性容器 */

  flex-direction: row; /* 主轴方向:row(默认)、row-reverse、column、column-reverse */
  flex-wrap: nowrap; /* 是否换行:nowrap(默认)、wrap、wrap-reverse */
  justify-content: flex-start; /* 主轴对齐方式:flex-start(默认)、flex-end、center、space-between、space-around、space-evenly */
  align-items: stretch; /* 交叉轴对齐方式:stretch(默认)、flex-start、flex-end、center、baseline */
  align-content: stretch; /* 多轴线对齐方式(仅当flex-wrap为wrap时有效) */
}

项目属性:

css
.item {
  order: 0; /* 排列顺序,数值越小越靠前 */
  flex-grow: 0; /* 放大比例,默认0不放大 */
  flex-shrink: 1; /* 缩小比例,默认1可缩小 */
  flex-basis: auto; /* 初始尺寸 */
  flex: 0 1 auto; /* flex-grow、flex-shrink、flex-basis的简写 */
  align-self: auto; /* 覆盖容器的align-items,单独设置对齐方式 */
}

8.2 Grid 布局

Grid(网格布局)是 CSS3 中引入的一种二维布局模型,用于创建更复杂的网格结构。

基本概念:

  • 容器(grid container):设置display: griddisplay: inline-grid的元素
  • 项目(grid item):容器的直接子元素
  • 网格线(grid line):定义网格的行和列边界
  • 网格轨道(grid track):两条相邻网格线之间的空间
  • 网格单元(grid cell):行和列交叉形成的区域
  • 网格区域(grid area):由多个网格单元组成的矩形区域

容器属性:

css
.container {
  display: grid; /* 块级网格容器 */
  display: inline-grid; /* 行内网格容器 */

  grid-template-columns: 1fr 2fr 1fr; /* 列宽 */
  grid-template-rows: 100px auto 50px; /* 行高 */
  grid-template-areas: "header header header" "sidebar main main" "footer footer footer"; /* 网格区域 */
  grid-column-gap: 20px; /* 列间距 */
  grid-row-gap: 10px; /* 行间距 */
  grid-gap: 10px 20px; /* 行间距和列间距的简写 */
  justify-content: start; /* 网格整体水平对齐方式 */
  align-content: start; /* 网格整体垂直对齐方式 */
  justify-items: start; /* 单个项目的水平对齐方式 */
  align-items: start; /* 单个项目的垂直对齐方式 */
}

项目属性:

css
.item {
  grid-column-start: 1; /* 列开始位置 */
  grid-column-end: 3; /* 列结束位置 */
  grid-row-start: 1; /* 行开始位置 */
  grid-row-end: 2; /* 行结束位置 */
  grid-column: 1 / 3; /* 列开始和结束位置的简写 */
  grid-row: 1 / 2; /* 行开始和结束位置的简写 */
  grid-area: header; /* 所在的网格区域名称 */
  justify-self: start; /* 项目自身的水平对齐方式 */
  align-self: start; /* 项目自身的垂直对齐方式 */
}

8.3 多列布局

  • columns:设置元素的列数和列宽
css
.multicolumn {
  columns: 3; /* 3列 */
  columns: 200px; /* 每列宽度200px */
  columns: 3 200px; /* 最多3列,每列至少200px */
}
  • column-count:设置元素的列数
css
.multicolumn {
  column-count: 3; /* 3列 */
}
  • column-width:设置元素的列宽
css
.multicolumn {
  column-width: 200px; /* 每列宽度200px */
}
  • column-gap:设置列之间的间距
css
.multicolumn {
  column-gap: 20px; /* 列间距20px */
}
  • column-rule:设置列之间的分隔线
css
.multicolumn {
  column-rule: 1px solid #333; /* 分隔线样式 */
}
  • column-span:设置元素是否跨越所有列
css
.heading {
  column-span: all; /* 跨越所有列 */
}

九、响应式设计与媒体查询

9.1 视口与单位

@viewport:设置视口的属性(已过时,建议使用元标签)

html
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

视口相关单位:

  • vw:视口宽度的 1%
  • vh:视口高度的 1%
  • vmin:视口宽度和高度中较小值的 1%
  • vmax:视口宽度和高度中较大值的 1%

9.2 媒体查询

@media:定义媒体查询,根据设备特性应用不同的样式

css
@media (max-width: 768px) {
  /* 屏幕宽度小于等于768px时应用的样式 */
  .sidebar {
    display: none;
  }

  .main-content {
    width: 100%;
  }
}

@media (min-width: 769px) and (max-width: 1024px) {
  /* 屏幕宽度在769px到1024px之间时应用的样式 */
  .sidebar {
    width: 25%;
  }

  .main-content {
    width: 75%;
  }
}

@media (orientation: portrait) {
  /* 竖屏模式 */
  .hero {
    height: 50vh;
  }
}

@media (orientation: landscape) {
  /* 横屏模式 */
  .hero {
    height: 100vh;
  }
}

常见媒体特性:

  • width:视口宽度
  • height:视口高度
  • device-width:设备屏幕宽度
  • device-height:设备屏幕高度
  • orientation:设备方向(portrait 或 landscape)
  • resolution:屏幕分辨率
  • prefers-color-scheme:用户偏好的颜色方案(light 或 dark)

9.3 容器查询

@container:定义容器查询,根据容器的大小应用不同的样式

css
.container {
  container-type: inline-size; /* 设置容器类型 */
}

@container (min-width: 600px) {
  /* 容器宽度大于等于600px时应用的样式 */
  .card {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

@container (max-width: 599px) {
  /* 容器宽度小于等于599px时应用的样式 */
  .card {
    display: block;
  }
}

十、CSS 变量与自定义属性

10.1 CSS 变量基础

  • --:定义 CSS 变量
css
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size-base: 16px;
}
  • var():使用 CSS 变量
css
body {
  color: var(--primary-color);
  font-size: var(--font-size-base);
}

.button {
  background-color: var(--primary-color);
  color: white;
  padding: 10px 20px;

  &:hover {
    background-color: var(--secondary-color);
  }
}
  • var()函数的第二个参数:设置变量的默认值
css
.box {
  color: var(--text-color, #333); /* 如果--text-color未定义,则使用#333 */
}

10.2 自定义属性

  • @property:定义自定义属性(CSS 变量的扩展)
css
@property --animation-progress {
  syntax: "<number>"; /* 定义类型 */
  inherits: false; /* 是否继承 */
  initial-value: 0; /* 初始值 */
}

.animated-element {
  animation: progress var(--animation-duration) linear;
  --animation-progress: 0;
}

@keyframes progress {
  to {
    --animation-progress: 1;
  }
}

十一、性能优化与最佳实践

11.1 CSS 优化策略

代码压缩:

  • 移除不必要的空格和注释
  • 缩短属性名和值
  • 使用 CSS 压缩工具(如 CSSNano、UglifyCSS)
  • 避免使用通配符选择器:
css
/* 不推荐 */
* {
  margin: 0;
  padding: 0;
}

/* 推荐 */
html,
body {
  margin: 0;
  padding: 0;
}
  • 避免过度嵌套:
css
/* 不推荐 */
.container .header .nav .menu-item {
  color: #333;
}

/* 推荐 */
.menu-item {
  color: #333;
}
  • 避免使用 @import:
css
/* 不推荐 */
@import "styles.css";

/* 推荐 */
<link rel="stylesheet" type="text/css" href="styles.css">

使用高效选择器:

  • 优先使用类选择器
  • 避免使用后代选择器,改用子代选择器
  • 避免使用属性选择器和伪类选择器,除非必要

CSS Sprites:

将多个小图标合并成一个图片,减少 HTTP 请求

css
.icon {
  background-image: url("sprite.png");
  background-repeat: no-repeat;
}

.home-icon {
  background-position: 0 0;
  width: 32px;
  height: 32px;
}

.contact-icon {
  background-position: -32px 0;
  width: 32px;
  height: 32px;
}

11.2 浏览器渲染优化

减少重排和重绘:

  • 批量修改元素样式
  • 使用transformopacity进行动画,避免触发重排
  • 使用will-change提示浏览器即将发生的变化
  • 分层渲染:
css
.accelerated {
  will-change: transform;
  transform: translateZ(0);
}
  • 使用content-visibility
  • 延迟渲染不可见区域的内容,提升长页面的加载速度
css
.lazy-section {
  content-visibility: auto;
  contain-intrinsic-size: 1000px;
}

十二、CSS 预处理器与后处理器

12.1 CSS 预处理器

Sass/SCSS:

  • 变量$primary-color: #3498db;
  • 嵌套
scss
.container {
  .header {
    .nav {
      list-style: none;

      li {
        display: inline-block;
      }
    }
  }
}
  • 混合宏
scss
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  @include flex-center;
}
  • 继承
scss
.button {
  padding: 10px 20px;
  border-radius: 5px;
}

.primary-button {
  @extend .button;
  background-color: #3498db;
  color: white;
}

Less:

  • 变量@primary-color: #3498db;
  • 嵌套
less
.container {
  .header {
    .nav {
      list-style: none;

      li {
        display: inline-block;
      }
    }
  }
}
  • 混合宏
less
.flex-center() {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  .flex-center();
}
  • 运算
less
@width: 100px;
.box {
  width: @width * 2;
}

12.2 CSS 后处理器

PostCSS:

  • 自动添加浏览器前缀(Autoprefixer)
  • 代码压缩(CSSNano)
  • 自定义插件开发

Autoprefixer 配置示例:

json
{
  "browsers": ["last 2 versions", "ie >= 11"]
}

十三、前沿技术与未来趋势

13.1 CSS 新特性

CSS 容器查询:

less
.container {
  container-type: inline-size;
}

@container (min-width: 600px) {
  .card {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

CSS 嵌套:

less
.container {
  .header {
    .nav {
      list-style: none;

      li {
        display: inline-block;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}

CSS View Transitions:

less
@view-transition {
  navigation: auto;
}

.nav {
  view-transition-name: --nav;
}

CSS Houdini: @property --hue {
  syntax: "<number>";
  initial-value: 0;
  inherits: false;
}

.color-shift {
  background: hsl(var(--hue), 100%, 50%);
  animation: hue-shift 5s infinite linear;
}

@keyframes hue-shift {
  to {
    --hue: 360;
  }
}

13.2 未来趋势

CSS 条件判断:

less
@if (max-width: 768px) {
  .sidebar {
    display: none;
  }
}

CSS 数学函数:

less
.box {
  width: calc(50% + 20px);
  height: clamp(100px, 50vh, 200px);
}

CSS 变量的更多控制:

less
@property --color {
  syntax: "<color>";
  inherits: false;
  initial-value: blue;
}

十四、CSS 架构与命名规范

14.1 CSS 架构模式

BEM 命名规范:

  • 块(Block):独立的组件
  • 元素(Element):块的子元素
  • 修饰符(Modifier):块或元素的变体
html
<!-- 块 -->
<div class="button">
  <!-- 元素 -->
  <span class="button__icon"></span>
  <!-- 元素 -->
  <span class="button__text">按钮</span>
</div>

<!-- 修饰符 -->
<div class="button button--primary">
  <span class="button__icon"></span>
  <span class="button__text">主要按钮</span>
</div>

SMACSS:

  • 基础(Base):通用样式
  • 布局(Layout):页面结构
  • 模块(Module):可复用的组件
  • 状态(State):动态样式
  • 主题(Theme):视觉主题

OOCSS:

  • 分离结构和外观
  • 分离容器和内容

14.2 CSS 代码组织

按功能分类:

  • base.css:基础样式
  • layout.css:布局样式
  • components.css:组件样式
  • utilities.css:工具类样式

按页面分类:

  • home.css:主页样式
  • about.css:关于页样式
  • contact.css:联系页样式

总结

CSS 作为网页设计的核心技术,其重要性不言而喻。通过本文的全面介绍,你已经掌握了从基础到高级的各种 CSS 属性和技术,包括文本与字体、盒模型、背景与颜色、列表与表格、用户界面、动画与过渡、高级布局、响应式设计等。

在实际开发中,应遵循最佳实践,合理使用各种 CSS 技术,注重性能优化,建立良好的代码组织和命名规范,以创建高效、可维护的网页样式。

随着 CSS 技术的不断发展,新的特性和功能将持续涌现,如 CSS 容器查询、CSS 嵌套、CSS View Transitions 等,这些都将进一步提升我们创建网页的能力和效率。

Released under the MIT License.