CSS 介绍

  • CSS 指的是层叠样式表(Cascading Style Sheet)

  • 核心的作用的是进行设置我们网页的基本的样式吧,以及美化我们的网页吧,核心就是做美化的讷

  • 以及CSS的书写方式

    • 嵌入式的书写形式

    • style 内部书写的形式

    • 外部链接引入的实现吧

CSS 创建

  • CSS 的话核心分为三类吧

    • 外部样式表(External Style Sheet)

      • 核心是通过我们的 link 标签实现引入的讷,以及实现对应的其他额外的操作的实现的讷

    • 内部样式表(Internal Style Sheet)

      • 核心就是通过我们的 head 标签中的 style 实现书写我们的内部的样式表吧

    • 内联样式表(Inline Style Sheet)

      • 核心就是通过我们的元素标签中指定 style 属性实现的指定元素的样式吧

  • 多重样式表

    • 核心的话就是通过我们的其他方式实现吧

    • 核心遵循的就是我们的解析的先后顺序吧,文档的解析流程吧,后的样式覆盖以前的样式吧

    • 核心还是解析规则决定了谁生效谁不生效吧

CSS 背景background

属性

核心作用

关键取值 / 用法

background-color

背景颜色(基础,必设降级方案)

十六进制(#fff)、RGB(rgb(255,255,255))、关键词(white)、透明(transparent

background-image

背景图片 / 渐变

图片(url("xxx.jpg"))、线性渐变(linear-gradient())、径向渐变(radial-gradient()

background-position

背景的位置

关键词(center/top left)、百分比(50% 50%)、像素(20px 30px

background-size

背景的尺寸

cover(覆盖容器)、contain(完整显示)、百分比 / 像素(100% 100%

background-repeat

背景是否重复

no-repeat(不重复,常用)、repeat-x/repeat-y(横向 / 纵向重复)

background-attachment

背景滚动行为

scroll(随内容滚动,默认)、fixed(固定不动,视差效果)

background-clip

背景的裁剪范围

border-box(默认,包含边框)、padding-box(不含边框)、content-box(仅内容区)、text(裁剪到文字,渐变文字常用)

background-origin

背景的定位原点

background-clip 的前 3 个值(控制 background-position 的参考点)

简写 background

合并以上属性

顺序:color image position/size repeat attachment origin clip(可选属性可省略)

  • CSS 的属性含有

    • background-color 实现的是指定我们背景的颜色吧

      • 可以设置的值有:字符串形式的颜色,十六进制的颜色,rgb|rgba

    • background-image 实现的就是指定我们背景的图片吧

      • 可以设置的是我们的 url 图片资源链接吧,以及我们的后面的渐变色这些吧

    • background-repeat 决定的就是背景是否重复吧

    • background-attachment 决定的就是背景是否固定吧

    • background-position 背景相对于的位置吧

/* 开始实现书写我们的样式吧 */
.container {
  background-color: red;  /* 设置的是背景的颜色吧 */
  background-image: url("./image.png");  // 设置的就是背景图片吧
  background-repeat: no-repeat;  // 背景不实现平铺吧
  background-position:right top;
}
  • 背景的混合书写实现吧

    • background: bg-color bg-image bg-repeat bg-attachment bg-position

      • 这个就是混合属性的时候书写的顺序吧

        • 颜色

        • 图片

        • 是否平铺

        • 是否固定

        • 相对位置吧

/* 正确:低饱和度渐变 + 深灰文字,高对比度,背景弱化 */
.good-card {
  width: 300px;
  padding: 2rem;
  /* 低饱和蓝紫渐变,柔和不刺眼 */
  background: linear-gradient(45deg, #e0e7ff, #f3e8ff);
  color: #1f2937; /* 深灰文字,对比度 7.2:1,达标 */
  font-size: 1rem;
  border-radius: 8px;
}

/* 进阶:深色背景 + 半透明遮罩,确保文字清晰 */
.dark-card {
  width: 300px;
  padding: 2rem;
  background: 
    /* 黑色遮罩(降低背景图亮度) */
    linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
    /* 背景图(风景图,复杂度高) */
    url("scenery.jpg") center/cover no-repeat;
  color: #fff; /* 白色文字,对比度 14:1,达标 */
  font-size: 1rem;
  border-radius: 8px;
}

/* 成功提示:绿色系(语义:安全、成功) */
.alert-success {
  padding: 1rem;
  background-color: #ecfdf5; /* 浅绿背景,柔和不刺眼 */
  border-left: 4px solid #10b981; /* 深绿边框,强化语义 */
  color: #065f46; /* 深绿文字,高对比度 */
}

/* 警告提示:黄色系(语义:注意、警示) */
.alert-warning {
  padding: 1rem;
  background-color: #fefce8; /* 浅黄背景 */
  border-left: 4px solid #f59e0b; /* 深黄边框 */
  color: #92400e; /* 深黄文字 */
}

/* 错误提示:红色系(语义:危险、错误) */
.alert-error {
  padding: 1rem;
  background-color: #fee2e2; /* 浅红背景 */
  border-left: 4px solid #ef4444; /* 深红边框 */
  color: #991b1b; /* 深红文字 */
}

/* 信息提示:蓝色系(语义:专业、信息) */
.alert-info {
  padding: 1rem;
  background-color: #eff6ff; /* 浅蓝背景 */
  border-left: 4px solid #3b82f6; /* 深蓝边框 */
  color: #1e40af; /* 深蓝文字 */
}

/* 全屏背景图,适配所有设备,核心图案不丢失 */
.hero-section {
  height: 100vh; /* 占满视口高度 */
  background: 
    linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)), /* 遮罩,确保文字清晰 */
    url("hero-background.jpg") center/cover no-repeat; /* 中心定位+覆盖容器 */
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

/* 移动设备优化:简化背景(去掉图案,保留渐变),减少加载压力 */
@media (max-width: 768px) {
  .hero-section {
    background: linear-gradient(135deg, #3b82f6, #1e40af); /* 纯色渐变替代背景图 */
  }
}

/* 卡片背景图,自适应卡片大小,不拉伸 */
.feature-card {
  width: 100%;
  max-width: 350px;
  height: 200px;
  background: url("card-pattern.jpg") center/cover no-repeat; /* 中心定位+覆盖容器 */
  border-radius: 8px;
  overflow: hidden; /* 隐藏裁剪部分 */
}

/* 另一种需求:背景图完整显示,不裁剪(用 contain) */
.avatar-card {
  width: 120px;
  height: 120px;
  background: url("avatar.jpg") center/contain no-repeat; /* 完整显示图片,不拉伸 */
  background-color: #f3f4f6; /* 背景图周围的填充色,避免空白 */
  border-radius: 50%;
}


/* 正确1:用 CSS 渐变替代纹理图片(性能最优) */
.texture-background {
  /* 用渐变模拟纹理,无加载成本 */
  background: linear-gradient(rgba(0,0,0,0.05) 1px, transparent 1px),
              linear-gradient(90deg, rgba(0,0,0,0.05) 1px, transparent 1px);
  background-size: 20px 20px; /* 纹理密度 */
}

/* 正确2:优化背景图(压缩为 WebP 格式,体积 < 200KB)+ 背景色占位 */
.optimized-background {
  /* 背景色占位,避免加载前空白 */
  background-color: #f3f4f6;
  /* 压缩后的 WebP 图片,加载快 */
  background-image: url("optimized-background.webp");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

/* 正确3:按需加载背景图(滚动时加载) */
.lazy-background {
  background-color: #f9fafb;
  /* 初始用占位图(小尺寸模糊图),滚动时替换为高清图 */
  background-image: url("placeholder-blur.jpg");
  background-position: center;
  background-size: cover;
}
/* JS 滚动加载逻辑(简化) */
document.addEventListener('scroll', () => {
  const elem = document.querySelector('.lazy-background');
  if (elem.getBoundingClientRect().top < window.innerHeight) {
    elem.style.backgroundImage = 'url("high-res-background.webp")';
  }
});


/* CSS:符合所有设计哲学的背景设计 */
.product-card {
  /* 1. 内容优先:低饱和背景+高对比度文字 */
  background: 
    /* 弱化背景图(遮罩+低透明度) */
    linear-gradient(rgba(255,255,255,0.85), rgba(255,255,255,0.85)),
    /* 2. 氛围匹配:科技感图案,传递产品属性 */
    url("tech-pattern.webp") center/cover no-repeat; /* 3. 性能优化:压缩后的 WebP 图片 */
  /* 4. 响应式适配:卡片宽度自适应,背景覆盖容器 */
  width: 100%;
  max-width: 380px;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.product-title {
  color: #111827; /* 深灰文字,对比度 8:1 */
  font-size: 1.5rem;
  margin-bottom: 1rem;
}

.product-desc {
  color: #4b5563; /* 中灰文字,对比度 5.2:1 */
  font-size: 1rem;
  line-height: 1.5;
  margin-bottom: 1.5rem;
}

.product-btn {
  /* 1. 语义匹配:蓝色=信任、购买 */
  background: linear-gradient(45deg, #3b82f6, #2563eb); /* 2. 渐进增强:渐变+纯色降级 */
  background-color: #3b82f6; /* 降级方案 */
  color: #fff; /* 对比度 14:1 */
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s ease;
}

.product-btn:hover {
  background: linear-gradient(45deg, #2563eb, #1d4ed8);
  background-color: #2563eb;
}

/* 响应式适配:小屏幕优化 */
@media (max-width: 768px) {
  .product-card {
    padding: 1.5rem;
    /* 简化背景:去掉图案,保留纯色,减少性能消耗 */
    background: #f9fafb;
  }
}

CSS 文本

  • 文本可以设置的属性含有

    • 文本的颜色值,通过 color 属性来设置和指定吧

      • 一般可以设置:颜色字符串,rgb或者rgba值,十六进制值

    • 文本的对齐方式,通过我们的 text-align 进行设置实现吧

      • 一般可以设置的为:center,left,right

    • 文本修饰符的值:text-decoration

      • 一般可以设置的值为:none,overline,line-throngth,underline

    • 文本转换试下:text-transform

      • 可以设置的值有:uppercase,lowercase,capitalize

    • 文本的缩进设置:text-indient

      • 设置的是文本的缩进属性吧,标准化一些吧

    • 文本排布的方向指定:direction

    • 文本的字符间距:letter-spacing

    • 文本阴影:text-shadow

    • 文本的垂直对其:vertical-align

    • 文本空白区域对其:white-space

    • 字间距:word-sapcing

字体全局设计

字体族设置思考

  • 对于我们的字体的设置的话,一般使用的是我们的 font-family 进行设置吧,以及设置的规则是

    • font-family: [首选字体], [...]

    • 优先使用的是系统的默认字体吧,然后指定通用字体

/* 网页正文字体栈:无衬线字体(现代清晰),兼容不同系统 */
body {
  font-family: 'Inter', 'SF Pro Display', 'PingFang SC', 'Microsoft YaHei', 
               Helvetica, Arial, sans-serif;
}

/* 标题字体栈:衬线字体(优雅正式),适配文章/博客标题 */
h1, h2, h3 {
  font-family: 'Georgia', 'Times New Roman', 'SimSun', serif;
}

字体大小设置

  • 这个在后期实现了我们的对应的移动端适配的能力实现吧

  • 核心使用的属性是 font-size 实现吧

/* 根元素设置基础字体(默认16px,这里重置为18px更易计算) */
html {
  font-size: 18px;
}

/* 正文:1rem = 18px,在任何设备上保持基础可读性 */
p {
  font-size: 1rem;
}

/* 标题:1.8rem = 32.4px,比正文大1.8倍,建立层次 */
h1 {
  font-size: 1.8rem;
}

/* 小文本:0.875rem = 15.75px,用于注释/辅助信息 */
small {
  font-size: 0.875rem;
}

/* 大屏适配:视口宽度>1200px时,标题放大 */
@media (min-width: 1200px) {
  h1 {
    font-size: 2.2rem; /* 39.6px */
  }
}

字体粗细指定

  • 核心是通过我们的 font-weight 进行的实现的吧,体现出美感来吧

/* 正文:常规粗细(400),易读 */
.article-content {
  font-weight: 400;
}

/* 小标题:半粗(600),比正文突出但不刺眼 */
.article-subtitle {
  font-weight: 600;
}

/* 大标题:粗体(700),视觉焦点 */
.article-title {
  font-weight: 700;
}

/* 强调文本:极粗(900),用于关键信息(如价格、警告) */
.highlight {
  font-weight: 900;
}

字体的样式指定

  • 核心是通过我们的 font-style 实现指定吧

  • 常见的可以设置的值有 normal italic oblique

/* blockquote 是 HTML 语义化标签(引用),用斜体区分 */
blockquote {
  font-style: italic;
  color: #666; /* 灰色弱化,不抢正文焦点 */
  border-left: 3px solid #eee;
  padding-left: 1rem;
}

字体间距设置

  • 核心的属性就是 line-height word-spacing letter-spacing

    • 一个是行高的设置

    • 一个单词间距的设置

    • 一个字体快的设置吧

/* 正文:1.5-1.6 是黄金行高,兼顾紧凑与呼吸感 */
.article {
  font-size: 1rem;
  line-height: 1.5; /* 实际行高 = 16px * 1.5 = 24px */
}

/* 标题:行高1.2-1.3,更紧凑,突出厚重感 */
h1 {
  font-size: 2rem;
  line-height: 1.2; /* 实际行高 = 32px * 1.2 = 38.4px */
}

/* 按钮文本:行高1,垂直居中(按钮高度=文本高度) */
.btn {
  font-size: 1rem;
  line-height: 1;
  padding: 0.5rem 1rem;
}

/* 多行文本垂直居中:父容器高度 = line-height * 行数 */
.card-title {
  height: 48px; /* 16px * 1.5 * 2 行 */
  line-height: 1.5;
  overflow: hidden; /* 隐藏超出部分 */
}

文本修饰

  • white-spaceoverflow-wrapword-breaktext-overflow

    • white-sapce 设置的空白区域的样式吧

    • overflow-wrap 设置的是我们的间距吧

    • overflow-wrap:优先在单词内部换行(保护单词完整性,推荐);

    • word-break:强制在任意字符间换行(可能拆分单词,慎用)。

/* 根元素基础字体(手机端 16px) */
html {
  font-size: 16px;
}

/* 正文样式 */
.article {
  max-width: 800px; /* 电脑端最大宽度,避免文本过长(一行超过 80 字符易疲劳) */
  margin: 0 auto; /* 居中 */
  padding: 0 1rem; /* 手机端左右内边距,避免贴边 */
  line-height: 1.5;
}

/* 平板端(768px+):基础字体放大到 17px */
@media (min-width: 768px) {
  html {
    font-size: 17px;
  }
}

/* 电脑端(1200px+):基础字体放大到 18px,行高调整为 1.6 */
@media (min-width: 1200px) {
  html {
    font-size: 18px;
  }
  .article {
    line-height: 1.6;
  }
}

CSS 链接

  • a:link - 正常,未访问过的链接

  • a:visited - 用户已访问过的链接

  • a:hover - 当用户鼠标放在链接上时

  • a:active - 链接被点击的那一刻

    • a:hover 必须跟在 a:link 和 a:visited后面

    • a:active 必须跟在 a:hover后面

/* 1. 未访问链接:蓝色,下划线 */
a:link {
  color: #2563eb; /* 蓝色(信任、可点击的语义) */
  text-decoration: underline;
}

/* 2. 已访问链接:紫色,保持下划线 */
a:visited {
  color: #7c3aed; /* 紫色(区分未访问) */
  /* 注意:不能修改 underline 样式,浏览器限制 */
}

/* 3. 悬停链接:深蓝,下划线变粗 */
a:hover {
  color: #1d4ed8;
  text-decoration-thickness: 2px; /* 下划线加粗 */
  text-underline-offset: 4px; /* 下划线与文字间距 */
}

/* 4. 点击瞬间:深蓝,下划线变色 */
a:active {
  color: #1e40af;
  text-decoration-color: #1e40af;
}
/* 高级下划线设计:细、偏移、hover 变色 */
a.custom-link {
  text-decoration: none; /* 取消默认下划线 */
  color: #2563eb;
  /* 自定义下划线:底部边框模拟(更灵活) */
  border-bottom: 2px solid #2563eb;
  padding-bottom: 2px; /* 文字与下划线间距 */
  transition: all 0.3s ease; /* 平滑过渡 */
}

a.custom-link:hover {
  color: #1d4ed8;
  border-bottom-color: #1d4ed8; /* 下划线跟随文字变色 */
}

/* 另一种方案:用 text-decoration 原生属性(更简洁) */
a.native-link {
  text-decoration: underline;
  text-decoration-style: solid;
  text-decoration-thickness: 1px; /* 细线条 */
  text-underline-offset: 3px; /* 偏移间距 */
  text-decoration-color: #93c5fd; /* 浅蓝下划线,不抢文字焦点 */
  color: #2563eb;
}

a.native-link:hover {
  text-decoration-thickness: 2px;
  text-decoration-color: #2563eb;
}
/* 全局基础链接样式(所有页面通用) */
a:link,
a:visited {
  color: #2563eb;
  text-decoration: underline;
  text-underline-offset: 3px;
  text-decoration-thickness: 1px;
}

a:hover,
a:focus {
  color: #1d4ed8;
  text-decoration-thickness: 2px;
}

a:active {
  color: #1e40af;
}

/* 特殊链接:导航链接(基于全局样式扩展) */
.nav-link:link,
.nav-link:visited {
  text-decoration: none; /* 取消下划线 */
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
}

.nav-link:hover,
.nav-link:focus {
  background-color: #eff6ff; /* 增加背景色,替代下划线 */
  color: #1d4ed8;
}

/* 特殊链接:按钮式链接(保持颜色一致) */
.btn-link:link,
.btn-link:visited {
  text-decoration: none;
  background-color: #2563eb;
  color: #fff;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  display: inline-block;
}

.btn-link:hover,
.btn-link:focus {
  background-color: #1d4ed8;
  color: #fff;
}

CSS 盒子模型

CSS box-model

  • 核心的话是四个区域吧

    • margin 外边距

    • border 边框

    • padding 内边距

    • content 内容区

盒子模型到底用来做什么讷?

  • 核心思想:在网页中实现呈现的任何的东西都是我们的一个一个的盒子而已,不管是什么,核心都是用来做的是进行吧元素进行包裹起来以及进行对应的排列布局一下吧

  • 核心模型核心实现规定了我们的盒子到底是如何进行排布和实现的讷

  • 核心的作用:统一元素的布局逻辑,实现开发者精准的控制元素的大小、间距和位置等信息吧

  • 那么此时就知道了元素的一些核心信息:元素实际占据的大小空间是 = content + padding + border + margin 吧

内容 content 区域

  • 盒子最内层,直接存放元素的实际内容(文本、图片、子元素等),是盒子的 “核心区域”

  • width:内容区的宽度(默认值 auto,由内容自动撑开);

  • height:内容区的高度(默认值 auto,由内容自动撑开)。

取值

含义

适用场景

auto

自动适应(默认)

文本段落、自适应容器

px

固定像素

固定尺寸的卡片、按钮

%

相对于父元素内容区的百分比

响应式布局(如占父容器 50% 宽度)

vw/vh

相对于视口的百分比

全屏元素(如首屏 banner)

min-width/max-width

最小 / 最大宽度(限制内容区尺寸)

避免元素过窄 / 过宽(如正文最小宽度 300px)

min-height/max-height

最小 / 最大高度

滚动容器(如聊天框最大高度 500px,超出滚动)

/* 固定尺寸的卡片:内容区宽300px、高200px */
.card {
  width: 300px;
  height: 200px;
  background-color: #f3f4f6;
}

/* 自适应内容的文本框:宽度自动,最大宽度600px(避免过宽) */
.text-box {
  max-width: 600px;
  width: auto;
  background-color: #eff6ff;
  padding: 1rem; /* 后续讲padding,先感受布局 */
}

/* 滚动容器:最小高度100px,最大高度300px(超出滚动) */
.scroll-container {
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto; /* 垂直滚动 */
  background-color: #fefce8;
}

padding 内边距

  • 简写:padding: 上 右 下 左(顺时针顺序,支持 1-4 个值);

  • 单独控制:padding-toppadding-rightpadding-bottompadding-left

/* 1. 简写用法(4个值:上1rem 右1.5rem 下1rem 左1.5rem) */
.card-padding {
  width: 300px;
  background-color: #f3f4f6;
  padding: 1rem 1.5rem; /* 上下内边距1rem,左右1.5rem */
}

/* 2. 简写用法(2个值:上下0.5rem,左右1rem) */
.btn-padding {
  display: inline-block;
  background-color: #2563eb;
  color: #fff;
  padding: 0.5rem 1rem; /* 上下小内边距,左右大内边距(按钮常用) */
  text-decoration: none;
  border-radius: 8px;
}

/* 3. 百分比内边距(响应式卡片:左右内边距占父元素宽度的5%) */
.responsive-padding {
  width: 80%;
  background-color: #fefce8;
  padding: 2% 5%; /* 上下2%,左右5%(父元素宽度越大,内边距越大) */
}

border 边框区域

  • 简写:border: 宽度 样式 颜色(三个属性缺一不可,否则边框不显示);

  • 单独控制:

    • 宽度:border-width(可拆分为 border-top-width 等);

    • 样式:border-style(必须有值,如 solid 实线、dashed 虚线,默认 none 无样式);

    • 颜色:border-color(默认继承父元素文本颜色);

  • 圆角:border-radius(控制边框圆角,常用 px 或百分比)。

/* 1. 基础边框(黑色实线,1px宽) */
.basic-border {
  width: 300px;
  padding: 1rem;
  border: 1px solid #000; /* 宽度1px + 实线 + 黑色 */
}

/* 2. 自定义边框(不同边不同样式) */
.custom-border {
  width: 300px;
  padding: 1rem;
  border-top: 2px solid #2563eb; /* 上边框:蓝色实线 */
  border-right: 1px dashed #9ca3af; /* 右边框:灰色虚线 */
  border-bottom: 2px solid #2563eb; /* 下边框:蓝色实线 */
  border-left: none; /* 左边框:无 */
}

/* 3. 圆角边框(卡片常用,8px圆角) */
.rounded-border {
  width: 300px;
  padding: 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px; /* 四角圆角,值越大越圆 */
  background-color: #f9fafb;
}

/* 4. 圆形边框(50%圆角,需配合正方形元素) */
.circle-border {
  width: 100px;
  height: 100px;
  border: 2px solid #8b5cf6;
  border-radius: 50%; /* 50% 圆角 = 圆形 */
  display: flex;
  align-items: center;
  justify-content: center;
}

margin 外边距

  • 盒子最外层,控制当前盒子与其他盒子之间的间距,相当于快递盒之间的 “空隙”—— 避免盒子挤在一起,提升布局的呼吸感

  • 简写:margin: 上 右 下 左(顺时针顺序,支持 1-4 个值);

  • 单独控制:margin-topmargin-rightmargin-bottommargin-left

  • 特殊用法:margin: 0 auto(水平居中,需配合固定宽度或 max-width)。

/* 1. 基础用法:上下间距2rem,左右间距1rem */
.card-margin {
  width: 300px;
  padding: 1rem;
  background-color: #f3f4f6;
  margin: 2rem 1rem; /* 上下2rem,左右1rem */
}

/* 2. 水平居中:margin: 0 auto(上下0,左右自动) */
.center-card {
  width: 300px; /* 必须有固定宽度或max-width */
  padding: 1rem;
  background-color: #eff6ff;
  margin: 0 auto; /* 水平居中,常用在页面主体、卡片 */
}

/* 3. 负值margin:让盒子超出父容器10px */
.negative-margin {
  width: 300px;
  padding: 1rem;
  background-color: #fefce8;
  margin-left: -10px; /* 向左超出父容器10px */
  margin-top: -10px; /* 向上超出父容器10px */
}

/* 4. 百分比margin:左右间距占父元素宽度的5% */
.responsive-margin {
  width: 80%;
  padding: 1rem;
  background-color: #f9fafb;
  margin: 2% auto; /* 上下2%,左右自动居中 */
}

盒子模型分类

(1)W3C 标准盒模型(默认)

  • 元素总宽度 = width(内容区宽度) + padding-left + padding-right + border-left + border-right

  • 元素总高度 = height(内容区高度) + padding-top + padding-bottom + border-top + border-bottom

  • 特点:widthheight 仅控制内容区大小,padding 和 border 会额外增加元素的总尺寸。

(2)IE 怪异盒模型(兼容旧版 IE)

  • 元素总宽度 = width(包含内容区 + padding + border);

  • 元素总高度 = height(包含内容区 + padding + border);

  • 特点:widthheight 控制整个盒子(内容 + padding+border) 的大小,padding 和 border 不会增加总尺寸,而是从内容区中 “挤压” 空间。

特性

W3C 标准盒模型(默认)

IE 怪异盒模型

控制属性

box-sizing: content-box(默认值)

box-sizing: border-box

总宽度计算

width(内容)+ padding + border

width(包含内容 + padding+border)

总高度计算

height(内容)+ padding + border

height(包含内容 + padding+border)

适用场景

需精准控制内容区大小

需固定元素总尺寸(如导航栏、卡片)

/* 全局设置:所有元素和伪元素都用 border-box */
*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0; /* 可选:重置默认margin/padding,避免浏览器差异 */
}

/* 全局重置(推荐) */
*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 卡片容器:水平居中,垂直间距 */
.card-container {
  max-width: 1200px;
  margin: 2rem auto; /* 水平居中 */
  padding: 0 1rem; /* 移动端左右内边距 */
}

/* 卡片样式:固定宽度,内边距,边框,外边距 */
.product-card {
  width: 300px;
  padding: 1.5rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #fff;
  margin: 0 auto 2rem; /* 水平居中,垂直间距2rem */
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.product-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.product-card h3 {
  margin-bottom: 0.5rem;
  color: #1f2937;
}

.product-card p {
  color: #6b7280;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.product-card .btn {
  display: inline-block;
  padding: 0.5rem 1rem;
  background-color: #2563eb;
  color: #fff;
  text-decoration: none;
  border-radius: 4px;
}

CSS display

display 的核心作用是「定义元素的 “显示行为模式”」—— 它回答了两个关键问题:

  1. 这个元素自己如何在页面中显示?(比如是独占一行,还是和其他元素并排?)

  2. 这个元素的子元素如何排列?(比如是水平排列、垂直排列,还是网格分布?)

类别

核心作用

代表属性值

「元素自身显示类型」

控制元素自身的显示形态(是否独占一行、是否支持宽高)

blockinlineinline-blocknone

「容器布局规则」

控制子元素的排列方式(一维 / 二维布局)

flex(一维)、grid(二维)、table(表格)

/* 响应式导航栏:大屏两端对齐,小屏垂直排列 */
.navbar {
  display: flex;
  flex-direction: row; /* 大屏:水平排列 */
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: #1f2937;
  color: #fff;
}

.navbar .logo {
  font-size: 1.2rem;
  font-weight: 600;
}

.navbar .links {
  display: flex;
  gap: 1.5rem;
}

.navbar a {
  color: #e5e7eb;
  text-decoration: none;
}

/* 小屏幕(768px以下):垂直排列 */
@media (max-width: 768px) {
  .navbar {
    flex-direction: column; /* 垂直排列 */
    gap: 1rem; /* 上下间距 */
  }
  
  .navbar .links {
    flex-direction: column;
    align-items: center; /* 链接水平居中 */
    gap: 0.5rem;
  }
}

CSS position

  1. position 的核心作用:定义元素的定位方式,控制元素的参考物、是否脱离文档流、位置偏移;

  2. 五大属性值核心特性

    • static:默认,遵循文档流,TRBL 无效;

    • relative:不脱离流,相对于自身偏移,保留原始空间;

    • absolute:脱离流,相对于定位祖先偏移,不占空间;

    • fixed:脱离流,相对于视口偏移,不随页面滚动;

    • sticky:未触发时遵循流,触发后固定,结合 relativefixed

  3. 关键规则

    • 定位元素支持 TRBL 和 z-index

    • absolute/fixed 会转为 block 特性,支持宽高;

    • sticky 生效需满足特定条件(触发条件、父容器规则);

  4. 核心关联positiondisplay(定位元素会改变 display 特性)、盒子模型(padding/border 仍有效,margin 规则不同)密切相关。

实战最佳实践

  1. 精准定位(弹窗、图标):用 absolute + 父容器 relative

  2. 固定在屏幕(导航栏、悬浮按钮):用 fixed,记得给内容留空间;

  3. 滚动吸顶(表头、标题):用 sticky,注意父容器规则;

  4. 轻微偏移(图标、按钮 hover):用 relative

  5. 层叠顺序:重要元素(弹窗、导航)设置高 z-index(如 999/9999);

  6. 避免滥用 absolute:过多绝对定位会导致布局混乱,优先用 flex/grid 布局,定位仅用于特殊场景。

window.addEventListener('scroll', () => {
  if (window.scrollY > 500) {
    document.body.classList.add('scroll-active');
  } else {
    document.body.classList.remove('scroll-active');
  }
});
/* 图片容器(relative 定位) */
.img-container {
  position: relative;
  width: 400px;
  height: 250px;
  margin: 2rem auto;
  border-radius: 8px;
  overflow: hidden; /* 隐藏超出容器的内容 */
}

.img-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 文字说明(绝对定位在图片底部) */
.img-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background-color: rgba(0, 0, 0, 0.6); /* 半透明背景,突出文字 */
  color: #fff;
  font-size: 1.1rem;
}
/* 弹窗遮罩层(覆盖整个视口) */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999; /* 确保在最上层 */
}

/* 弹窗内容(相对遮罩层居中) */
.modal-content {
  position: relative; /* 作为关闭按钮的定位祖先 */
  width: 350px;
  padding: 1.5rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

/* 关闭按钮(绝对定位在弹窗右上角) */
.modal-close {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #6b7280;
  text-decoration: none;
  border-radius: 50%;
  background-color: #f3f4f6;
}

CSS overflow

描述

visible

默认值。内容不会被修剪,会呈现在元素框之外。

hidden

内容会被修剪,并且其余内容是不可见的。

scroll

内容会被修剪,但是浏览器会显示滚动条以便查看其余的内容。

auto

如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容。

inherit

规定应该从父元素继承 overflow 属性的值。

CSS 选择器

选择器

语法

作用

示例

注意点

元素选择器

element

匹配指定标签名的所有元素

div { ... } 匹配所有 <div>

优先级最低,适合全局样式(如重置样式)

类选择器

.class

匹配带指定 class 的所有元素

.btn { ... } 匹配 <div class="btn">

复用性最强,推荐优先使用(语义化命名)

ID 选择器

#id

匹配唯一带指定 id 的元素

#header { ... } 匹配 <header id="header">

优先级极高(100),不可复用,谨慎使用

通配符选择器

*

匹配页面所有元素

* { margin: 0; padding: 0; }

性能最差(遍历所有节点),避免全局滥用

内联样式

style=""

元素内部直接定义样式

<div style="color: red">

优先级最高(1000),维护性差,仅临时使用

!important

property: val !important

强制提升单个属性优先级

.btn { color: red !important; }

打破优先级规则,谨慎使用(仅用于覆盖第三方样式)

选择器

语法

关系描述

示例

性能 / 场景提示

后代选择器

A B

匹配 A 的所有后代 B(包括子、孙)

nav .link { ... } 匹配 nav 内所有 .link

灵活但性能一般,避免嵌套过深(如 A B C D

子选择器

A > B

匹配 A 的直接子元素 B(仅一代)

ul > li { ... } 匹配 ul 直接子级 li

性能优于后代选择器,适合精准子元素定位

相邻兄弟选择器

A + B

匹配 A 的紧接其后的同级 B

.card + .card { margin-top: 1rem; }

用于同级元素的相邻间距 / 样式切换

通用兄弟选择器

A ~ B

匹配 A 的所有后续同级 B

.active ~ .tab { display: none; }

用于批量控制后续同级元素(如标签页切换)

交集选择器

A.B

同时满足 A 和 B(无空格)

div.card { ... } 匹配 <div class="card">

精准度高,避免样式污染

选择器语法

作用描述

示例

适用场景

[attr]

匹配拥有 attr 属性的元素

[disabled] { cursor: not-allowed; }

禁用状态的表单元素

[attr="val"]

匹配 attr 属性值完全等于 val 的元素

[type="button"] { ... }

特定类型的表单控件(按钮、输入框)

[attr^="val"]

匹配 attr 属性值以 val 开头的元素

[href^="https"] { color: #2563eb; }

外部链接样式(https 开头)

[attr$="val"]

匹配 attr 属性值以 val 结尾的元素

[src$=".png"] { border: 1px solid #eee; }

特定后缀的资源(图片、文件)

[attr*="val"]

匹配 attr 属性值包含 val 字符串的元素

[class*="icon-"] { display: inline-block; }

匹配带特定前缀的类(如图标类)

[attr~="val"]

匹配 attr 属性值包含 val 单词的元素(空格分隔)

[class~="active"] { ... }

多类名元素中匹配特定类(如状态类)

`[attr

="val"]`

匹配 attr 属性值以 val- 开头或等于 val 的元素

`[lang

="en"] { ... }`

多语言网站(如 en、en-US)

选择器

语法

作用描述

示例

兼容性 / 性能提示

否定选择器

:not(selector)

匹配不满足 selector的元素

input:not([disabled]) { cursor: pointer; }

CSS3 特性,兼容性良好;支持多参数(not(a,b),CSS4)

目标选择器

:target

匹配当前 URL 锚点对应的元素

#tab1:target { display: block; }

用于锚点导航、标签页切换(无需 JS)

根元素选择器

:root

匹配文档根元素(HTML 中为 <html>

:root { --primary: #2563eb; }

定义全局 CSS 变量(推荐用法)

空元素选择器

:empty

匹配 无任何子元素(含文本) 的元素

div:empty { display: none; }

隐藏空容器(如动态加载的列表)

范围选择器

:nth-child(n)

匹配父元素的第 n 个子元素

li:nth-child(2n) { background: #f9fafb; }

n 支持数字、公式(2n = 偶数)、关键词(odd/even)

反向范围选择器

:nth-last-child(n)

从父元素最后一个子元素开始计数

li:nth-last-child(1) { margin-right: 0; }

选中最后几个元素(如移除最后一个元素的右边距)

伪类

语法

触发条件

示例

注意点

:hover

element:hover

鼠标悬浮在元素上

.btn:hover { transform: scale(1.05); }

桌面端有效,移动端需谨慎(触发延迟)

:active

element:active

元素被激活(点击按下时)

.btn:active { transform: scale(0.95); }

顺序建议:link -> visited -> hover -> active

:focus

element:focus

元素获得焦点(键盘 / 点击)

input:focus { outline: 2px solid #2563eb; }

必须配合 tabindex 用于非表单元素

:focus-visible

element:focus-visible

仅当焦点 “可见” 时(键盘导航)触发

button:focus-visible { outline: 2px solid #2563eb; }

替代 :focus,优化 UX(点击时无轮廓)

:focus-within

element:focus-within

元素或其后代获得焦点时触发

.form-group:focus-within { border-color: #2563eb; }

用于表单组高亮(如输入框聚焦时标签高亮)

:link

a:link

未访问过的链接

a:link { color: #2563eb; }

仅对 <a> 有效,需在 :visited 前定义

:visited

a:visited

已访问过的链接

a:visited { color: #8b5cf6; }

受隐私限制,仅支持 color/background 等少量属性

:enabled

element:enabled

表单元素处于启用状态

input:enabled { background: #fff; }

对应 disabled 属性的反向状态

:disabled

element:disabled

表单元素处于禁用状态

input:disabled { background: #f3f4f6; }

常用于禁用按钮、输入框的样式

伪类

语法

作用描述

示例

进阶用法

:first-child

parent > element:first-child

匹配父元素的第一个子元素(不限类型)

ul > li:first-child { margin-top: 0; }

注意:若第一个子元素不是 li,则不匹配

:last-child

parent > element:last-child

匹配父元素的最后一个子元素

div > p:last-child { margin-bottom: 0; }

用于移除最后一个元素的底部间距

:only-child

parent > element:only-child

匹配父元素的唯一子元素

div:only-child { width: 100%; }

适用于单元素容器(如独生子元素的卡片)

:first-of-type

parent > element:first-of-type

匹配父元素中该类型的第一个子元素

div > p:first-of-type { font-weight: bold; }

区别于 :first-child:仅看元素类型,不看位置

:last-of-type

parent > element:last-of-type

匹配父元素中该类型的最后一个子元素

div > span:last-of-type { color: #6b7280; }

用于同类型元素的最后一个样式调整

:only-of-type

parent > element:only-of-type

匹配父元素中该类型的唯一子元素

header > h1:only-of-type { text-align: center; }

适用于独一类型的标题、图标等

:nth-child(n)

parent > element:nth-child(n)

父元素的第 n 个子元素(n 支持数字 / 公式 / 关键词)

tr:nth-child(odd) { background: #f9fafb; }

公式:2n(偶数)、2n+1(奇数)、-n+3(前 3 个)

:nth-last-child(n)

parent > element:nth-last-child(n)

从父元素末尾开始计数的第 n 个子元素

li:nth-last-child(-n+2) { margin-right: 0; }

选中最后 2 个元素(移除右边距)

:nth-of-type(n)

parent > element:nth-of-type(n)

父元素中该类型的第 n 个子元素

p:nth-of-type(3) { color: #2563eb; }

忽略其他类型元素,仅对目标类型计数

:nth-last-of-type(n)

parent > element:nth-last-of-type(n)

从父元素末尾开始计数的该类型第 n 个子元素

img:nth-last-of-type(1) { margin-bottom: 0; }

选中最后一个图片(移除底部间距)

伪类

语法

作用描述

示例

适用场景

:lang(lang)

element:lang(lang)

匹配指定语言的元素(基于 lang 属性)

p:lang(en) { quotes: "" ""; }

多语言网站的文本样式适配

:dir(dir)

element:dir(dir)

匹配指定文本方向的元素(ltr/rtl)

div:dir(rtl) { text-align: right; }

阿拉伯语、希伯来语等从右到左的语言适配

:blank

element:blank

匹配空值的表单元素(输入框无内容)

input:blank { background: #f3f4f6; }

区别于 :empty,仅对表单元素有效(CSS4)

:current()

element:current()

匹配当前激活的元素(如音频 / 视频的当前轨道)

track:current { color: #2563eb; }

多媒体控件自定义样式

:past()/:future()

element:past()/:future()

匹配时间线中 “过去”/“未来” 的元素(如日历)

event:past() { opacity: 0.6; }

日历、时间轴组件

伪元素

语法

作用描述

示例

进阶技巧

::before

element::before

在元素内容前插入虚拟元素

.btn::before { content: "→"; margin-right: 4px; }

1. content 是必需属性(空值 "" 也可);2. 默认 inline,需转为 inline-block 才能设置宽高

::after

element::after

在元素内容后插入虚拟元素

.tag::after { content: "x"; cursor: pointer; }

1. 常用于清除浮动(clear: both);2. 实现图标、装饰线等

::first-line

element::first-line

匹配元素的第一行文本

p::first-line { font-weight: bold; font-size: 1.2em; }

仅对块级元素有效,支持的样式有限(如 color/font,不支持 padding/border

::first-letter

element::first-letter

匹配元素的第一个字符

h2::first-letter { font-size: 2em; float: left; }

用于首字下沉、装饰效果,仅对块级元素有效

::selection

element::selection

匹配用户选中的文本

::selection { background: #2563eb; color: #fff; }

1. 全局使用(无元素前缀)匹配所有选中文本;2. 支持 background/color 等少量属性

::placeholder

element::placeholder

匹配输入框的占位文本

input::placeholder { color: #9ca3af; font-size: 0.9em; }

1. 需加浏览器前缀(::-webkit-input-placeholder);2. 不可继承父元素样式

::file-selector-button

input::file-selector-button

匹配文件上传框的选择按钮

input[type="file"]::file-selector-button { padding: 0.5rem; border: none; border-radius: 4px; }

自定义文件上传按钮样式(CSS4,兼容性良好)

::marker

element::marker

匹配列表项(li)的项目符号 / 编号

ul li::marker { color: #2563eb; font-size: 1.5em; }

自定义列表符号颜色、大小,支持 color/font 样式

::backdrop

element::backdrop

匹配全屏元素(如 dialog)的背景层

dialog::backdrop { background: rgba(0,0,0,0.7); }

自定义弹窗、视频全屏时的背景层(配合 <dialog> 标签)

1. 选择器优先级规则(必记)

  • 优先级计算:!important(最高,打破规则)> 内联样式(1000)> ID 选择器(100)> 类 / 属性 / 伪类选择器(10)> 元素 / 伪元素选择器(1)> 通配符(0);

  • 优先级叠加:组合选择器的优先级 = 各组成部分优先级之和(如 div#header .nav = 1 + 100 + 10 = 111);

  • 同优先级:后定义的样式覆盖先定义的(或遵循 “就近原则”);

  • 最佳实践:避免滥用 !important 和 ID 选择器,优先用类选择器(复用性强)和结构伪类(减少冗余类名)。

2. 性能优化建议

  • 避免过度嵌套:选择器嵌套越深,浏览器匹配效率越低(如 body .container .row .col .card .title 应简化为 .card-title);

  • 避免通配符和复杂属性选择器:*[attr*="val"] 会遍历所有元素,大型项目慎用;

  • 优先使用 “精准选择器”:如用 #header 不如用 .header(可复用),用 .btn-primary 不如用 button[data-type="primary"](语义化更强);

  • 结构伪类性能:nth-child(n)nth-of-type(n) 略快(浏览器无需筛选元素类型)。

3. 兼容性注意事项

  • 新特性兼容性::has()(CSS4)、:user-invalid(CSS4)、::file-selector-button(CSS4)在现代浏览器(Chrome 88+、Firefox 85+、Safari 15.4+)中支持良好,无需兼容旧浏览器时可大胆使用;

  • 伪元素前缀:::placeholder 需要加浏览器前缀(::-webkit-input-placeholder for Chrome/Safari,::-moz-placeholder for Firefox);

  • 旧浏览器兼容:若需兼容 IE11,需避免 :nth-child() 的复杂公式、:focus-visible:has() 等特性。

4. 语义化与可维护性

  • 类名语义化:避免 .red.left 等样式描述类,优先用 .error.sidebar 等语义类;

  • 伪类 / 伪元素复用:用伪元素实现装饰、图标等,减少额外 DOM 节点(如用 ::before 代替 <i class="icon">);

  • 组件化样式:结合 CSS 变量和伪类,实现组件的状态切换(如 .btn 配合 :hover/:active/:disabled 覆盖所有状态)。

总结

  1. 选择器:核心是 “精准匹配”,优先使用类选择器和组合选择器,高级选择器(:has()、属性选择器)可大幅提升开发效率,减少冗余 DOM;

  2. 伪类:核心是 “状态 / 关系匹配”,无需操作 DOM 即可实现动态样式(如表单验证、hover 效果),:focus-within:user-invalid 等新特性可优化用户体验;

  3. 伪元素:核心是 “创建虚拟元素”,适合实现装饰、图标、清除浮动等功能,减少 DOM 层级,提升页面性能;

  4. 最佳实践:优先级合理控制、避免过度嵌套、语义化命名、善用新特性(CSS4+),兼顾性能、可维护性和兼容性。

CSS 媒体查询

类别

媒体特性语法

作用描述

适用场景

示例代码片段

屏幕宽度(最常用)

min-width: [数值]

屏幕宽度≥数值时生效(从小到大适配)

移动端→平板→桌面端布局切换

@media (min-width: 768px) { 平板样式 }

max-width: [数值]

屏幕宽度≤数值时生效(从大到小适配)

桌面端→平板→移动端布局切换

@media (max-width: 767px) { 移动端样式 }

设备方向

orientation: landscape

设备横屏(宽度 > 高度)时生效

横屏时调整布局(如表单横向排列)

@media (orientation: landscape) { 横屏样式 }

orientation: portrait

设备竖屏(高度 > 宽度)时生效

竖屏时调整布局(如表单纵向排列)

@media (orientation: portrait) { 竖屏样式 }

系统外观

prefers-color-scheme: dark

系统开启暗色模式时生效

暗色模式适配(切换背景 / 文字色)

@media (prefers-color-scheme: dark) { 暗色样式 }

prefers-color-scheme: light

系统开启亮色模式时生效(默认)

亮色模式基础样式

@media (prefers-color-scheme: light) { 亮色样式 }

辅助功能

prefers-contrast: high

系统开启高对比度模式时生效

无障碍适配(增强对比度)

@media (prefers-contrast: high) { 高对比度样式 }

prefers-reduced-motion: reduce

系统开启减少动画模式时生效

关闭非必要动画(如 hover 缩放、过渡)

@media (prefers-reduced-motion: reduce) { 无动画样式 }

设备交互类型

pointer: coarse

触摸设备(如手机、平板)时生效

增大点击区域(按钮、链接)

@media (pointer: coarse) { .btn { padding: 0.8rem; } }

pointer: fine

精确指针设备(如鼠标)时生效

正常尺寸交互元素

@media (pointer: fine) { .btn { padding: 0.5rem; } }

宽高比

aspect-ratio: [比例]

屏幕宽高比匹配时生效(如 16:9、4:3)

宽屏 / 窄屏专属布局(如视频播放器、仪表盘)

@media (aspect-ratio: 16/9) { 宽屏样式 }

打印样式

print(媒体类型)

打印文档时生效

隐藏导航 / 按钮,优化打印布局(如显示 URL)

@media print { .no-print { display: none; } }

分辨率

min-resolution: [数值]dpi

屏幕分辨率≥数值时生效(如高清屏)

高清屏适配(如 2x 图、字体调整)

@media (min-resolution: 192dpi) { 高清屏样式 }

视口高度

min-height: [数值]

视口高度≥数值时生效(如长屏手机)

调整垂直布局(如侧边栏高度)

@media (min-height: 800px) { 长屏样式 }

逻辑运算符组合

(条件1) and (条件2)

同时满足多个条件时生效

精准适配(如平板横屏)

@media (min-width: 768px) and (orientation: landscape) { 平板横屏样式 }

(条件1), (条件2)

满足任一条件时生效

多场景共用样式(如手机横屏 + 平板竖屏)

@media (max-width: 768px) or (orientation: portrait) { 共用样式 }

CSS3

  • grid 布局

  • flex 布局

  • transition

  • keysframe

  • media 这些都是比较重要的讷