Skip to content

CSS 介绍与语法:为网页注入样式的艺术

什么是 CSS?

CSS(Cascading Style Sheets,层叠样式表)是用来描述 HTML 文档样式的语言。如果说 HTML 是网页的骨架,那么 CSS 就是网页的外观和服装,它决定了网页的颜色、字体、布局、动画等视觉表现。

想象一下装修房子:

  • HTML 就像是房子的结构(墙壁、门窗、房间划分)
  • CSS 就像是房子的装修设计(墙面颜色、家具摆放、装饰风格)
css
/* CSS 规则示例 */
h1 {
  color: #2c3e50; /* 文字颜色:深蓝灰色 */
  font-size: 2.5rem; /* 字体大小:2.5倍根字体大小 */
  text-align: center; /* 文本居中对齐 */
  margin-bottom: 20px; /* 下边距:20像素 */
}

p {
  line-height: 1.6; /* 行高:1.6倍字体大小 */
  color: #333; /* 文字颜色:深灰色 */
}

CSS 的核心作用

1. 内容与表现分离

CSS 实现了网页内容和视觉表现的分离,这是现代 Web 开发的核心理念之一:

html
<!-- HTML 负责结构和内容 -->
<article class="blog-post">
  <h1>文章标题</h1>
  <p>这是文章的内容段落...</p>
</article>
css
/* CSS 负责样式和表现 */
.blog-post {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.blog-post h1 {
  color: #2c3e50;
  border-bottom: 3px solid #3498db;
  padding-bottom: 10px;
}

2. 层叠特性

CSS 的"层叠"特性允许多个样式规则应用于同一个元素,并按照特定优先级规则确定最终样式:

css
/* 多个样式规则可以应用于同一个元素 */
p {
  color: blue; /* 基础样式 */
  font-size: 16px; /* 基础样式 */
}

.article-content p {
  color: #333; /* 更具体的样式,会覆盖上面的 blue */
}

.article-content p.important {
  color: red; /* 最具体的样式,优先级最高 */
  font-weight: bold;
}

CSS 的发展历史

早期探索(1994-1996)

CSS 的诞生源于对网页美化的需求。在早期,网页样式主要通过 HTML 标签的属性来控制,这种方式存在很多问题:

html
<!-- 早期的内联样式方式(不推荐) -->
<h1><font color="red" size="6" face="Arial">标题</font></h1>
<p><font color="blue" size="3">段落文本</font></p>

关键时间节点

  • 1994 年:Håkon Wium Lie 提出了 CSS 的初步构想
  • 1996 年:CSS Level 1 成为 W3C 推荐标准
  • 1998 年:CSS Level 2 发布

CSS 2.1 成熟期(1998-2011)

CSS 2.1 成为最稳定和广泛支持的版本,引入了定位、浮动、表格布局等重要特性:

css
/* CSS 2.1 的经典特性 */
.container {
  position: relative; /* 相对定位 */
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.sidebar {
  position: absolute; /* 绝对定位 */
  right: 0;
  top: 0;
  width: 250px;
}

.main-content {
  margin-right: 270px; /* 为侧边栏留出空间 */
}

.float-element {
  float: left; /* 浮动布局 */
  width: 50%;
  margin-right: 20px;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both; /* 清除浮动 */
}

CSS 3 革命时代(2009-至今)

CSS 3 采用模块化开发,各个功能模块可以独立发展。这个时期引入了许多革命性的特性:

弹性布局(Flexbox)

css
.flex-container {
  display: flex; /* 弹性容器 */
  justify-content: space-between; /* 主轴对齐 */
  align-items: center; /* 交叉轴对齐 */
  gap: 20px; /* 间距 */
}

.flex-item {
  flex: 1; /* 弹性伸缩 */
  min-width: 0; /* 防止溢出 */
}

网格布局(Grid)

css
.grid-container {
  display: grid; /* 网格容器 */
  grid-template-columns: 1fr 2fr 1fr; /* 列定义 */
  grid-template-rows: auto 1fr auto; /* 行定义 */
  gap: 20px; /* 网格间距 */
}

.grid-item {
  grid-column: span 2; /* 跨列 */
  grid-row: 1 / 3; /* 跨行 */
}

CSS 变量

css
:root {
  --primary-color: #3498db; /* CSS 变量定义 */
  --secondary-color: #2ecc71;
  --spacing-unit: 8px;
  --border-radius: 4px;
}

.button {
  background: var(--primary-color);
  padding: calc(var(--spacing-unit) * 2);
  border-radius: var(--border-radius);
}

CSS 语法结构

基本语法规则

CSS 规则由选择器和声明块组成:

css
/*    选择器       声明块 */
/*      |           |     */
/*      v           v     */
h1 {
  /* 选择器:选择要应用样式的元素 */
  color: blue; /* 声明:属性: 值 */
  font-size: 24px; /* 声明:属性: 值 */
  margin: 10px 0; /* 声明:属性: 值 */
} /* 声明块结束 */

选择器的类型

1. 基本选择器

css
/* 元素选择器 */
h1 {
  color: blue;
}

/* 类选择器 */
.highlight {
  background: yellow;
}

/* ID 选择器 */
#header {
  position: fixed;
  top: 0;
}

/* 通用选择器 */
* {
  box-sizing: border-box;
}

2. 组合选择器

css
/* 后代选择器 */
.container p {
  margin: 15px 0;
}

/* 子元素选择器 */
.menu > li {
  display: inline-block;
}

/* 相邻兄弟选择器 */
h1 + p {
  font-weight: bold;
}

/* 属性选择器 */
input[type="text"] {
  border: 1px solid #ccc;
}

3. 伪类和伪元素选择器

css
/* 伪类选择器 */
a:hover {
  color: red;
}
a:active {
  transform: scale(0.95);
}
li:nth-child(odd) {
  background: #f9f9f9;
}

/* 伪元素选择器 */
p::first-line {
  font-weight: bold;
}
.button::before {
  content: "★ ";
}

属性和值

CSS 属性控制元素的各种视觉特性:

css
.text-styling {
  /* 字体相关 */
  font-family: "Helvetica Neue", Arial, sans-serif;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.5;
  color: #333;
  text-align: justify;

  /* 背景和边框 */
  background-color: #fff;
  background-image: url("pattern.png");
  border: 1px solid #ddd;
  border-radius: 8px;

  /* 内外边距 */
  padding: 20px;
  margin: 15px 0;

  /* 尺寸和定位 */
  width: 100%;
  height: auto;
  max-width: 600px;
  position: relative;
}

CSS 的层叠和继承

层叠规则

当多个 CSS 规则应用于同一个元素时,浏览器按照以下规则确定最终样式:

  1. 重要性:!important 声明优先级最高
  2. 特殊性:选择器越具体,优先级越高
  3. 源代码顺序:后面定义的规则覆盖前面定义的规则
css
/* 优先级示例 */
p {
  color: gray;
} /* 优先级: 0,0,0,1 */
p.content {
  color: black;
} /* 优先级: 0,0,1,1 */
div article p.content {
  color: blue;
} /* 优先级: 0,0,1,3 */
#main p.content {
  color: red;
} /* 优先级: 0,1,1,1 */
p.important {
  color: green !important;
} /* 优先级最高 */

继承机制

某些 CSS 属性会自动从父元素继承到子元素:

css
/* 可以继承的属性 */
body {
  font-family: Arial, sans-serif; /* 子元素会继承字体 */
  color: #333; /* 子元素会继承文字颜色 */
  line-height: 1.6; /* 子元素会继承行高 */
}

/* 不会继承的属性 */
body {
  margin: 0; /* 子元素不会继承外边距 */
  padding: 0; /* 子元素不会继承内边距 */
  border: none; /* 子元素不会继承边框 */
  background: white; /* 子元素不会继承背景 */
}

CSS 的引入方式

1. 内联样式

直接在 HTML 标签中定义样式(不推荐大量使用):

html
<h1 style="color: blue; font-size: 24px;">标题</h1>
<p style="margin: 15px 0;">段落内容</p>

2. 内部样式表

在 HTML 文档的 <head> 部分定义样式:

html
<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        font-family: Arial, sans-serif;
        line-height: 1.6;
        color: #333;
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <!-- 页面内容 -->
  </body>
</html>

3. 外部样式表(推荐)

将样式定义在独立的 CSS 文件中:

css
/* styles.css */
body {
  font-family: "Helvetica Neue", Arial, sans-serif;
  line-height: 1.6;
  color: #333;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
html
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <!-- 页面内容 -->
  </body>
</html>

CSS 的现代特性

1. CSS 变量(自定义属性)

CSS 变量使得样式更加灵活和可维护:

css
:root {
  /* 定义全局变量 */
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --text-color: #2c3e50;
  --bg-color: #ecf0f1;
  --border-radius: 8px;
  --spacing-sm: 8px;
  --spacing-md: 16px;
  --spacing-lg: 24px;
}

.card {
  background: var(--bg-color);
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.card-title {
  color: var(--primary-color);
  margin-bottom: var(--spacing-sm);
}

/* JavaScript 可以动态修改 CSS 变量 */
/* document.documentElement.style.setProperty('--primary-color', '#e74c3c'); */

2. 响应式设计

媒体查询使得网页能够适应不同的设备和屏幕尺寸:

css
/* 移动优先的响应式设计 */
.container {
  width: 100%;
  padding: 0 15px;
  margin: 0 auto;
}

/* 平板设备 */
@media (min-width: 768px) {
  .container {
    max-width: 750px;
    padding: 0 30px;
  }
}

/* 桌面设备 */
@media (min-width: 1024px) {
  .container {
    max-width: 970px;
    padding: 0 40px;
  }
}

/* 大屏设备 */
@media (min-width: 1200px) {
  .container {
    max-width: 1170px;
  }
}

3. CSS Grid 和 Flexbox

现代布局技术让复杂布局变得简单:

css
/* Flexbox 用于组件内部布局 */
.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.nav-item {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.nav-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* Grid 用于页面整体布局 */
.page-layout {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 250px 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
  gap: 20px;
}

.header {
  grid-area: header;
}
.sidebar {
  grid-area: sidebar;
}
.main {
  grid-area: main;
}
.footer {
  grid-area: footer;
}

CSS 最佳实践

1. 命名规范

使用清晰的类名和结构化的命名方式:

css
/* BEM 命名方法论 */
.card {
} /* 块 */
.card__title {
} /* 块__元素 */
.card__content {
} /* 块__元素 */
.card--featured {
} /* 块--修饰符 */
.card__title--large {
} /* 块__元素--修饰符 */

/* 功能性命名 */
.text-center {
  text-align: center;
}
.mb-0 {
  margin-bottom: 0;
}
.p-4 {
  padding: 1rem;
}
.hidden {
  display: none;
}

2. 代码组织

保持 CSS 代码的清晰和可维护性:

css
/* ==========================================================================
   基础样式
   ========================================================================== */

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

/* Typography */
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  line-height: 1.6;
  color: #333;
}

/* ==========================================================================
   组件样式
   ========================================================================== */

/* Buttons */
.btn {
  display: inline-block;
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn--primary {
  background: #3498db;
  color: white;
}

.btn--primary:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

3. 性能优化

编写高效的 CSS 代码:

css
/* 避免过度嵌套 */
/* 不推荐 */
.container .header .nav .menu .item .link {
}

/* 推荐 */
.nav-link {
}

/* 使用高效的属性 */
/* 推荐 */
transform: translateX(20px);

/* 不推荐(会触发重排) */
left: 20px;

/* 合理使用 !important */
/* 避免 */
.text {
  color: red !important;
}

/* 在特殊情况下使用 */
.modal-overlay {
  z-index: 9999 !important; /* 确保模态框总是在最上层 */
}

总结

CSS 是前端开发中不可或缺的技术,它不仅仅是为网页添加颜色和样式,更是实现复杂布局、交互动画和响应式设计的关键工具。

本节要点回顾

  • CSS 是层叠样式表,负责网页的视觉表现
  • CSS 实现了内容与表现的分离,提高了代码的可维护性
  • CSS 的层叠特性决定了多个样式规则的优先级
  • 现代 CSS 3 提供了强大的布局工具(Flexbox、Grid)和动画能力
  • CSS 变量和响应式设计使得样式更加灵活和适应性更强
  • 良好的 CSS 编写规范和代码组织对项目维护至关重要

掌握 CSS 的基础语法和核心概念,是构建美观、现代网页应用的基础。