CSS 核心技术解析:从选择器到属性值的完整指南

198 阅读11分钟

CSS 核心技术解析:从选择器到属性值的完整指南

作为前端开发的三大基石之一,CSS 的重要性不言而喻。本文将系统讲解 CSS 的核心语法结构,通过丰富的代码示例帮助您掌握选择器、属性和值的专业用法。

一、CSS 基础语法结构

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

selector {
  property: value;
  /* 注释 */
}

代码示例解析

/* 选中所有 <p> 元素 */
p {
  color: blue;      /* 文本颜色 */
  font-size: 16px;  /* 字体大小 */
  margin: 10px 0;   /* 外边距 */
}

二、CSS 选择器详解

2.1 基本选择器

选择器类型语法示例匹配目标
元素选择器p所有`` 元素
类选择器.introclass="intro" 的元素
ID 选择器#headerid="header" 的元素
通用选择器*所有元素
/* 元素选择器 */
h1 {
  font-weight: bold;
}

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

/* ID 选择器 */
#main-content {
  width: 80%;
}

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

2.2 关系选择器

选择器类型语法示例匹配目标
后代选择器div pdiv 内部所有 p 元素
子代选择器ul > liul 的直接子元素 li
相邻兄弟h1 + p紧接在 h1 后的 p 元素
通用兄弟h1 ~ ph1 之后的所有同级 p 元素
/* 后代选择器 */
article p {
  line-height: 1.6;
}

/* 子代选择器 */
nav > ul {
  list-style: none;
}

/* 相邻兄弟选择器 */
h2 + p {
  margin-top: 0;
}

/* 通用兄弟选择器 */
h2 ~ p {
  color: #666;
}

2.3 属性选择器

/* 存在属性 */
[disabled] {
  opacity: 0.5;
}

/* 精确匹配 */
[type="text"] {
  border: 1px solid #ccc;
}

/* 包含字符串 */
[class*="btn"] {
  padding: 8px 12px;
}

/* 开头匹配 */
[href^="https"] {
  color: green;
}

/* 结尾匹配 */
[src$=".png"] {
  border: 1px solid #eee;
}

2.4 伪类选择器

伪类描述
:hover鼠标悬停状态
:active激活状态
:focus获得焦点
:disabled禁用状态
:first-child第一个子元素
:last-child最后一个子元素
:nth-child(n)第 n 个子元素
:not(selector)反向选择
/* 链接状态 */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { text-decoration: underline; }

/* 表单元素状态 */
input:focus {
  outline: 2px solid #3498db; /* 聚焦状态 */
}
input:disabled {
  background-color: #f5f5f5; /* 禁用状态 */
}
input:checked + label {
  font-weight: bold; /* 复选框选中时 */
}

/* 结构化伪类 */
li:first-child { 
  font-weight: bold; /* 列表第一项 */
}
li:last-child {
  border-bottom: none; /* 列表最后项 */
}
tr:nth-child(odd) {
  background-color: #f9f9f9; /* 奇数行 */
}
p:nth-of-type(2) {
  font-style: italic; /* 第二个<p>元素 */
}

/* 否定伪类 */
div:not(.special) {
  border: 1px solid #ddd;
}

2.5 伪元素选择器

伪元素作用描述示例代码
::before元素内容前插入生成内容p::before { content: "→ "; }
::after元素内容后插入生成内容a::after { content: " ↗"; }
::first-line选择文本的第一行(受容器宽度影响)p::first-line { font-weight: bold; }
::first-letter选择文本块的首字母h1::first-letter { font-size: 2em; color: red; }
::selection选择用户鼠标高亮选中的文本::selection { background: yellow; color: black; }
::placeholder选择表单输入框的占位文本input::placeholder { color: #999; }
::marker选择列表项(<li>)或<summary>前的标记符号(项目符号/数字)li::marker { color: blue; }

关键特性详解

  1. ::before/::after

    • 必须配合 content 属性(空内容需写 content: ""
    • 默认是行内元素,可改变显示方式
    .tooltip::after {
      content: "提示文本";
      display: block;
      background: #333;
      color: white;
      padding: 5px;
    }
    
  2. ::first-line/::first-letter

    • 仅适用于块级容器(如 div, p, h1 等)
    • 响应式效果:::first-line 是CSS中的一个伪元素,它允许您为 *文本块的第一行* 设置特殊样式。这个选择器最强大的特性是它的响应式行为——当容器宽度改变时,应用样式的第一行范围会自动调整 随窗口大小变化
    article::first-letter {
      float: left;
      font-size: 3em;
      line-height: 1;
      margin-right: 5px;
    }
    
  3. ::selection: 选择用户**鼠标高亮选中的文本**

    • 仅支持有限属性:color, background, text-shadow, cursor(部分浏览器支持)text-decoration(部分浏览器支持)
    pre::selection {
      background: #ff6; /* 代码块选中时为黄色 */
    }
    

    注意:伪元素生成的内容不会出现在DOM中,仅用于视觉呈现,屏幕阅读器可能无法识别(需确保关键信息不依赖伪元素)。

与伪类选择器的区别

类型作用对象语法典型代表
伪元素元素的特定部分::::before, ::first-line
伪类元素的特定状态::hover, :nth-child()
/* 伪类:基于状态 */
a:hover { color: red; } 

/* 伪元素:选择内容片段 */
a::before { content: "🔗"; }
/* 首字母 */
p::first-letter {
  font-size: 150%;
}

/* 首行 */
p::first-line {
  font-weight: bold;
}

/* 前后内容 */
blockquote::before {
  content: "“";
  font-size: 2em;
}

/* 选中文本 */
::selection {
  background: yellow;
  color: black;
}

三、CSS 属性与值详解

3.1 常用属性分类

文本属性
p {
  font-family: "Helvetica", Arial, sans-serif;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  text-align: center;
  text-decoration: none;
  color: #333;
}
盒模型属性
+-----------------------------------------+
|                margin                   |
|  +-----------------------------------+  |
|  |             border                |  |
|  |  +-----------------------------+  |  |
|  |  |         padding             |  |  |
|  |  |  +-----------------------+  |  |  |
|  |  |  |      content          |  |  |  |
|  |  |  +-----------------------+  |  |  |
|  |  +-----------------------------+  |  |
|  +-----------------------------------+  |
+-----------------------------------------+
.box {
  /* 尺寸属性 */
  width: 300px;
  height: 200px;
  min-width: 250px; /* 最小宽度 */
  max-height: 500px; /* 最大高度 */
  
  /* 内边距 */
  padding: 20px; /* 所有边 */
  padding: 10px 20px; /* 上下 左右 */
  padding: 5px 10px 15px 20px; /* 上 右 下 左 */
  
  /* 外边距 */
  margin: 0 auto; /* 水平居中 */
  margin-top: 20px;
  
  /* 边框 */
  border: 2px solid #3498db; /* 宽度 样式 颜色 */
  border-radius: 10px; /* 圆角 */
  border-top-left-radius: 5px; /* 单独控制 */
  
  /* 背景 */
  background-color: #f8f9fa;
  background-image: url("bg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  
  /* 盒模型模式 */
  box-sizing: border-box; /* content-box(默认) | border-box */
}
背景属性
header {
  background-color: #f8f8f8;
  background-image: url("bg.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
布局属性
.container {
  /* 定位 */
  position: relative; /* static | relative | absolute | fixed | sticky */
  top: 10px;
  left: 20px;
  z-index: 10; /* 堆叠顺序 */
  
  /* 弹性盒 */
  display: flex;
  flex-direction: row; /* row | row-reverse | column | column-reverse */
  justify-content: space-between; /* 主轴对齐 */
  align-items: center; /* 交叉轴对齐 */
  flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
  
  /* 网格布局 */
  display: grid;
  grid-template-columns: 1fr 2fr 1fr; /* 列定义 */
  grid-template-rows: 100px auto; /* 行定义 */
  grid-gap: 20px; /* 网格间隙 */
  
  /* 浮动 */
  float: left; /* left | right | none */
  clear: both; /* 清除浮动 */
  
  /* 显示模式 */
  display: block; /* block | inline | inline-block | none */
  visibility: visible; /* visible | hidden */
}
过渡与变换
.button {
  /* 过渡效果 */
  transition-property: background-color, transform; /* 指定属性 */
  transition-duration: 0.3s; /* 持续时间 */
  transition-timing-function: ease-in-out; /* 时间函数 */
  transition-delay: 0.1s; /* 延迟 */
  
  /* 简写 */
  transition: all 0.3s ease-in-out;
  
  /* 变换 */
  transform: translateX(10px); /* 位移 */
  transform: rotate(15deg); /* 旋转 */
  transform: scale(1.1); /* 缩放 */
  transform: skew(10deg); /* 倾斜 */
  
  /* 组合变换 */
  transform: translateY(-50%) rotate(5deg);
  
  /* 变换原点 */
  transform-origin: left top;
}
动画属性
@keyframes slide-in {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  80% {
    transform: translateX(10%);
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

.element {
  /* 应用动画 */
  animation-name: slide-in;
  animation-duration: 0.8s;
  animation-timing-function: ease-out;
  animation-delay: 0.2s;
  animation-iteration-count: 1; /* infinite | 数值 */
  animation-direction: normal; /* normal | reverse | alternate | alternate-reverse */
  animation-fill-mode: forwards; /* none | forwards | backwards | both */
  
  /* 简写 */
  animation: slide-in 0.8s ease-out 0.2s 1 normal forwards;

3.2 值类型详解

颜色值
.color-examples {
  color: red;                  /* 关键字 */
  color: #ff0000;              /* 十六进制 */
  color: rgb(255, 0, 0);       /* RGB */
  color: rgba(255, 0, 0, 0.5); /* RGBA */
  color: hsl(0, 100%, 50%);    /* HSL */
}
CSS单位
.units {
  padding: 15px;    /* 像素 */
  line-height: 1.5; /* 无单位,倍数 */

  /* 相对单位 */
  font-size: 1.2rem; /* 相对于根元素字体大小 */
  margin: 2em; /* 相对于当前元素字体大小 */
  width: 80%; /* 相对于父元素宽度 */
  height: 50vh; /* 相对于视口高度的50% */
  width: 100vw; /* 相对于视口宽度的100% */
  
  /* 新单位 */
  width: min(100%, 1200px); /* 取最小值 */
  gap: clamp(10px, 2vw, 20px); /* 在10px-20px之间,基于2vw计算 */
  
  /* 角度单位 */
  transform: rotate(45deg); /* 度 */
  transform: rotate(0.25turn); /* 圈 */
  
  /* 时间单位 */
  transition-duration: 300ms; /* 毫秒 */
  animation-duration: 1.5s; /* 秒 */
}
变量(自定义属性)
/* 定义全局变量 */
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --spacing-unit: 8px;
  --max-width: 1200px;
}

/* 使用变量 */
.button {
  background-color: var(--primary-color);
  padding: calc(var(--spacing-unit) * 2); /* 计算 */
  max-width: var(--max-width);
}

/* 局部变量 */
.card {
  --card-shadow: 0 4px 8px rgba(0,0,0,0.1);
  box-shadow: var(--card-shadow);
}
函数值
.functions {
  width: calc(100% - 40px);
  transform: rotate(45deg);
  background: linear-gradient(to right, red, blue);
  color: var(--main-color); /* CSS变量 */
}

四、CSS 特性与层叠

4.1 优先级计算

优先级由 A,B,C,D 四个级别决定:

  • A: 内联样式 (1,0,0,0)
  • B: ID 选择器 (0,1,0,0)
  • C: 类/伪类/属性选择器 (0,0,1,0)
  • D: 元素/伪元素选择器 (0,0,0,1)
/* 优先级: 0,1,0,1 */
#nav li.active {
  color: red;
}

/* 优先级: 0,0,2,1 */
ul.menu li:hover {
  color: blue;
}

4.2 继承与控制

body {
  font-family: Arial; /* 可继承属性,如文本属性(font-*、color、line-height、text-transform、white-space) */
  color: #333;       /* 可继承属性 */
  border: 1px solid;  /* 非继承属性 ,如盒模型属性、背景属性、定位属性、显示属性、text-decoration`, `vertical-align`*/
}

/* 强制继承 */
div {
  border: inherit;
}

/* 重置继承 */
p {
  color: initial;
}

五、响应式设计基础

5.1 媒体查询

/* 基本结构 media-type对应值有 screen ... */
@media media-type and (media-feature) {
  /* CSS规则 */
}

/* 示例1:最大宽度 */
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  .menu {
    display: none;
  }
}

/* 示例2:屏幕方向 */
@media (orientation: portrait) {
  .header {
    height: 60vh;
  }
}

/* 示例3:多条件组合 */
@media (min-width: 1024px) and (prefers-color-scheme: dark) {
  body {
    background-color: #1a1a1a;
    color: #f0f0f0;
  }
}

/* 示例4:打印样式 */
@media print {
  .no-print {
    display: none;
  }
  body {
    font-size: 12pt;
  }
}

5.2 响应式布局技巧

/* 响应式网格 */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

/* 弹性图片 */
img {
  max-width: 100%;
  height: auto;
}

/* 响应式文本 */
h1 {
  font-size: clamp(1.5rem, 5vw, 2.5rem);
}

/* 断点管理 */
/* 小屏幕: <576px (默认) */
.container { padding: 10px; }

/* 中等屏幕: ≥576px */
@media (min-width: 576px) {
  .container { padding: 15px; }
}

/* 大屏幕: ≥992px */
@media (min-width: 992px) {
  .container { padding: 20px; }
}

六、实战代码示例

6.1 导航菜单

<nav class="main-nav">
  <ul>
    <li><a href="#">首页</a></li>
    <li><a href="#">产品</a></li>
    <li class="active"><a href="#">服务</a></li>
    <li><a href="#">关于</a></li>
  </ul>
</nav>
.main-nav {
  background-color: #333;
}

.main-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

.main-nav li {
  position: relative;
}

.main-nav a {
  display: block;
  padding: 1rem 1.5rem;
  color: white;
  text-decoration: none;
}

.main-nav a:hover {
  background-color: #555;
}

.main-nav .active a {
  background-color: #0066cc;
}

.main-nav li:not(:last-child)::after {
  content: "|";
  color: #666;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

6.2 卡片组件

<div class="card">
  <img src="product.jpg" alt="产品图片" class="card-img">
  <div class="card-body">
    <h3 class="card-title">产品名称</h3>
    <p class="card-text">产品描述内容...</p>
    <button class="btn">立即购买</button>
  </div>
</div>
.card {
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  transition: transform 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
}

.card-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.card-body {
  padding: 1.5rem;
}

.card-title {
  margin-top: 0;
  margin-bottom: 0.5rem;
  font-size: 1.25rem;
}

.card-text {
  color: #666;
  margin-bottom: 1rem;
}

.btn {
  display: inline-block;
  padding: 0.5rem 1rem;
  background-color: #0066cc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:hover {
  background-color: #0055aa;
}

七、专业建议与最佳实践

  1. 命名规范

    • 使用 BEM (Block__Element--Modifier) 等命名方法
    • 保持命名语义化且一致
  2. 组织代码

    /* 1. 重置和基础样式、变量 */
    *, *::before, *::after {
      box-sizing: border-box;
    }
    
    :root { --primary-color: #0066cc; }
    
    body {
      margin: 0;
      font-family: system-ui, sans-serif;
    }
    
    /* 2. 工具类 */
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
    }
    
    .text-center {
      text-align: center;
    }
    
    /* 3. 组件样式 */
    .button {
      display: inline-block;
      padding: 10px 20px;
      /* ... */
    }
    
    .card {
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      /* ... */
    }
    
    /* 4. 页面特定样式 */
    .homepage-banner {
      height: 400px;
      background: linear-gradient(to right, #3498db, #2c3e50);
    }
    
    /* 5. 媒体查询 */
    @media (max-width: 768px) {
      .homepage-banner {
        height: 300px;
      }
    }
    

    居中技巧

    /* 水平居中 */
    .block-center {
      margin: 0 auto; /* 块级元素 */
    }
    
    .inline-center {
      text-align: center; /* 行内元素 */
    }
    
    /* 绝对定位居中 */
    .absolute-center {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    /* Flexbox居中 */
    .flex-center {
      display: flex;
      justify-content: center; /* 水平 */
      align-items: center;     /* 垂直 */
    }
    
    /* Grid居中 */
    .grid-center {
      display: grid;
      place-items: center; /* 水平垂直居中 */
    }
    

    清除浮动

    /* 现代方法 - 使用伪元素 */
    .clearfix::after {
      content: "";
      display: table;
      clear: both;
    }
    
    /* 父元素设置 */
    .parent {
      overflow: auto; /* 触发BFC */
    }
    

    防止文本溢出

    .ellipsis {
      white-space: nowrap;      /* 不换行 */
      overflow: hidden;         /* 隐藏溢出 */
      text-overflow: ellipsis;  /* 显示省略号 */
    }
    
    .multi-line-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 3;    /* 限制行数 */
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
  3. 性能优化

    • 避免过度嵌套选择器
    • 使用简写属性
    • 减少不必要的重绘
  4. 浏览器兼容性

    .example {
      display: -webkit-flex; /* 旧版 Safari */
      display: flex;        /* 标准语法 */
    }
    
  5. 现代 CSS 特性

    • CSS Grid 布局
    • CSS 自定义属性 (变量)
    • CSS 逻辑属性 (如 margin-inline-start)

总结:CSS学习路径建议

  1. 基础阶段​:掌握选择器、盒模型、常用属性
  2. 布局阶段​:深入学习Flexbox和Grid布局
  3. 响应式阶段​:掌握媒体查询和响应式单位
  4. 进阶阶段​:学习CSS变量、动画、变换等
  5. 优化阶段​:掌握CSS架构和性能优化技巧

推荐资源​:

实践建议​:每天编写CSS代码,尝试实现不同布局效果,使用浏览器开发者工具进行调试和优化。遇到问题时,记住CSS的核心原则是"层叠"和"继承",理解这两个概念能解决80%的问题。