CSS 3 样式与布局

精选 CSS 3 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 本速查表列出了 CSS 选择器语法、属性、单位和其他实用信息。

#🚀 入门指引

#简介

CSS 功能丰富,不仅仅是页面布局。

外部样式表

<link href="./path/to/stylesheet/style.css" rel="stylesheet" type="text/css" />

内部样式表

<style>
  body {
    background-color: linen;
  }
</style>

行内样式

<h2 style="text-align: center;">Centered text</h2>

<p style="color: blue; font-size: 18px;">Blue, 18-point text</p>

#添加类名

<div class="classname"></div>
<div class="class1 classn ..."></div>

支持在同一元素上使用多个类名。

#强制优先 (!important)

.post-title {
  color: blue !important;
}

覆盖所有之前的样式规则。

#选择器

h1 {
}
#job-title {
}
div.hero {
}
div > p {
}

参阅: 选择器

#文本颜色

color: #2a2aff;
color: green;
color: rgb(34, 12, 64, 0.6);
color: hsla(30 100% 50% / 0.6);

参阅: 颜色

#背景

background-color: blue;
background-image: url('nyan-cat.gif');
background-image: url('../image.png');

参阅: 背景

#字体

.page-title {
  font-weight: bold;
  font-size: 30px;
  font-family: 'Courier New';
}

参阅: 字体

#定位

.box {
  position: relative;
  top: 20px;
  left: 20px;
}

另见: 定位 Position

#动画

animation: 300ms linear 0s infinite;

animation: bounce 300ms linear infinite;

参阅: 动画

#注释

/* 这是单行注释 */

/* 这是
   多行注释 */

#Flex 布局

div {
  display: flex;
  justify-content: center;
}
div {
  display: flex;
  justify-content: flex-start;
}

参阅: Flexbox | Flex 技巧

#Grid 布局

#container {
  display: grid;
  grid: repeat(2, 60px) / auto-flow 80px;
}

#container > div {
  background-color: #8ca0ff;
  width: 50px;
  height: 50px;
}

参阅: Grid 布局

#变量 & 计数器

counter-set: subsection;
counter-increment: subsection;
counter-reset: subsection 0;

:root {
  --bg-color: brown;
}
element {
  background-color: var(--bg-color);
}

参阅: 动态内容

#CSS 选择器

#💡 实用示例

分组选择器

h1,
h2 {
  color: red;
}

链式选择器

h3.section-heading {
  color: blue;
}

属性选择器

div[attribute='SomeValue'] {
  background-color: red;
}

首个子元素选择器

p:first-child {
  font-weight: bold;
}

空元素选择器

.box:empty {
  background: lime;
  height: 80px;
  width: 80px;
}

参见: 类型 Type /

#基础选择器

* 所有元素
div 所有 div 标签
.classname 所有带有该类名的元素
#idname 具有该 ID 的元素
div,p 所有 div 和 p 标签
#idname * #idname 内的所有元素

另见: 类型 / / ID / 通用 选择器

#组合选择器

参见: 相邻兄弟 Adjacent /

选择器 说明
div.classname 具有特定类名的 div
div#idname 具有特定 ID 的 div
div p div 内部的 p 标签
div > p div 内一级深度的
所有 p 标签
div + p 紧跟 div 之后的 p 标签
div ~ p div 之后的兄弟 p 标签

另见: 相邻兄弟 / 一般兄弟 / 子元素 选择器

#属性选择器

参见: 属性选择器 Attribute selectors

a[target] 具有 target 属性的元素
a[target="_blank"] 在新标签页中打开
a[href^="/index"] /index 开头
[class | ="chair"] chair 开头
[class*="chair"] 包含 chair
[title~="chair"] 包含单词 chair
a[href$=".doc"] .doc 结尾
[type="button"] 指定类型

另见: 属性选择器

#用户行为伪类

a:link 正常状态的链接
a:active 被点击状态的链接
a:hover 鼠标悬停的链接
a:visited 已访问的链接

#伪类

p::after 在 p 之后添加内容
p::before 在 p 之前添加内容
p::first-letter p 的首字母
p::first-line p 的首行
::selection 用户选中的内容
::placeholder Placeholder 属性
:root 文档根元素
:target 高亮活动锚点
div:empty 没有子元素的元素
p:lang(en) 具有 en 语言属性的 p
:not(span) 不是 span 的元素

#Input 伪类

input:checked 选中的输入框
input:disabled 禁用的输入框
input:enabled 启用的输入框
input:focus 获得焦点的输入框
input:in-range 值在范围内
input:out-of-range 值超出范围
input:valid 值有效的输入框
input:invalid 值无效的输入框
input:可选 没有 必填 属性
input:必填 具有 必填 属性
input:read-only 具有 readonly 属性
input:read-write 没有 readonly 属性
input:indeterminate 处于 indeterminate 状态

#结构伪类

p:first-child 第一个子元素
p:last-child 最后一个子元素
p:first-of-type 某类型的第一个
p:last-of-type 某类型的最后一个
p:nth-child(2) 父元素的第二个子元素
p:nth-child(3n42) Nth-child (an + b) 公式
p:nth-last-child(2) 倒数第二个子元素
p:nth-of-type(2) 父元素的第二个 p
p:nth-last-of-type(2) ...倒数
p:only-of-type 父元素中唯一的该类型
p:only-child 父元素的唯一子元素

#CSS 字体

#属性

参见: 字体 Font

属性名称 属性说明
font-family: <font> <fontN>
font-size: <size>
letter-spacing: <size>
line-height: <number>

| font-weight: | <number> / bold / normal | | font-style: | italic / normal | | text-decoration: | underline / none |

| text-align: | left / right
center / justify | | text-transform: | capitalize / uppercase / lowercase |

另见: 字体 Font

#简写

style weight size (必填) line-height family
font: italic 400 14px / 1.5 sans-serif
style weight size (必填) line-height family (必填)

#示例

font-family: Arial, sans-serif;
font-size: 12pt;
letter-spacing: 0.02em;

#大小写转换

/* Hello */
text-transform: capitalize;

/* HELLO */
text-transform: uppercase;

/* hello */
text-transform: lowercase;

#自定义字体 (@font-face)

@font-face {
  font-family: 'Glegoo';
  src: url('../Glegoo.woff');
}

参见: 字体

#CSS 颜色

#命名颜色

color: red;
color: orange;
color: tan;
color: rebeccapurple;

#十六进制颜色

color: #090;
color: #009900;
color: #090a;
color: #009900aa;

#rgb() 颜色

color: rgb(34, 12, 64, 0.6);
color: rgba(34, 12, 64, 0.6);
color: rgb(34 12 64 / 0.6);
color: rgba(34 12 64 / 0.3);
color: rgb(34 12 64 / 60%);
color: rgba(34.6 12 64 / 30%);

#HSL 颜色

color: hsl(30, 100%, 50%, 0.6);
color: hsla(30, 100%, 50%, 0.6);
color: hsl(30 100% 50% / 0.6);
color: hsla(30 100% 50% / 0.6);
color: hsl(30 100% 50% / 60%);
color: hsla(30.2 100% 50% / 60%);

#其他

color: inherit;
color: initial;
color: unset;
color: transparent;

color: currentcolor; /* 关键字 */

#CSS 背景

#属性

属性名称 属性说明
background: (简写)

| background-color: | 参阅: 颜色 | | background-image: | url(...) | | background-position: | left/center/right
top/center/bottom | | background-size: | cover X Y | | background-clip: | border-box
padding-box
content-box | | background-repeat: | no-repeat
repeat-x
repeat-y | | background-attachment: | scroll/fixed/local |

#简写

color image positionX positionY size repeat attachment
background: #ff0 url(a.jpg) left top / 100px auto no-repeat fixed;
background: #abc url(b.png) center center / cover repeat-x local;
color image posX posY size repeat attach..

#💡 实用示例

background: url(img_man.jpg) no-repeat center;

background:
  url(img_flwr.gif) right bottom no-repeat,
  url(paper.gif) left top repeat;

background: rgb(2, 0, 36);
background: linear-gradient(
  90deg,
  rgba(2, 0, 36, 1) 0%,
  rgba(13, 232, 230, 1) 35%,
  rgba(0, 212, 255, 1) 100%
);

#CSS 盒模型

#最大/最小值

.column {
  max-width: 200px;
  width: 500px;
}

另见: max-width / min-width / max-height / min-height

#外边距 / 内边距

.block-one {
  margin: 20px;
  padding: 10px;
}

另见: 外边距 Margin / 内边距 Padding

#盒模型 (Box-sizing)

.container {
  box-sizing: border-box;
}

另见: 盒模型 Box-sizing

#可见性

.invisible-elements {
  visibility: hidden;
}

另见: 可见性 Visibility

#auto 关键字

div {
  margin: auto;
}

另见: 外边距 Margin

#溢出处理

.small-block {
  overflow: scroll;
}

另见: 溢出 Overflow

#CSS 动画

#简写

name duration timing-function delay count direction fill-mode play-state
animation: bounce 300ms linear 100ms infinite alternate-reverse both reverse
name duration timing-function delay count direction fill-mode play-state

#属性

参见: 动画 Animation

属性
animation: (简写)
animation-name: <name>
animation-duration: <time>ms
animation-timing-function: ease / linear / ease-in / ease-out / ease-in-out
animation-delay: <time>ms
animation-iteration-count: infinite / <number>
animation-direction: normal / reverse / alternate / alternate-reverse
animation-fill-mode: none / forwards / backwards / both / initial / inherit
animation-play-state: normal / reverse / alternate / alternate-reverse

另见: 动画 Animation

#示例

/* @keyframes duration | timing-function | delay |
   iteration-count | direction | fill-mode | play-state | name */
animation: 3s ease-in 1s 2 reverse both paused slidein;

/* @keyframes duration | timing-function | delay | name */
animation: 3s linear 1s slidein;

/* @keyframes duration | name */
animation: 3s slidein;

animation: 4s linear 0s infinite alternate move_eye;
animation: bounce 300ms linear 0s infinite normal;
animation: bounce 300ms linear infinite;
animation: bounce 300ms linear infinite alternate-reverse;
animation: bounce 300ms linear 2s infinite alternate-reverse forwards normal;

#JavaScript 事件

.one('webkitAnimationEnd oanimationend msAnimationEnd animationend')

#CSS Flexbox 弹性盒

#简单示例

.container {
  display: flex;
}
.container > div {
  flex: 1 1 auto;
}

#容器

.container {

display: flex;
display: inline-flex;
flex-direction: row; /* 从左到右 - 默认 */
flex-direction: row-reverse; /* 从右到左 */
flex-direction: column; /* 从上到下 */
flex-direction: column-reverse; /* 从下到上 */
flex-wrap: nowrap; /* 单行 */
flex-wrap: wrap; /* 多行 */
align-items: flex-start; /* 垂直对齐到顶部 */
align-items: flex-end; /* 垂直对齐到底部 */
align-items: center; /* 垂直居中 */
align-items: stretch; /* 所有子元素等高 (默认) */
justify-content: flex-start; /* [xxx        ] */
justify-content: center; /* [    xxx    ] */
justify-content: flex-end; /* [        xxx] */
justify-content: space-between; /* [x    x    x] */
justify-content: space-around; /* [ x   x   x ] */
justify-content: space-evenly; /* [  x  x  x  ] */

}

#子元素

.container > div {

/* 以下写法: */
flex: 1 0 auto;

/* 等价于: */
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
order: 1;
align-self: flex-start; /* 左对齐 */
margin-left: auto; /* 右对齐 */

}

#CSS Flexbox 技巧

#垂直居中

.container {
  display: flex;
}

.container > div {
  width: 100px;
  height: 100px;
  margin: auto;
}

#垂直居中 (2)

.container {
  display: flex;

  /* 垂直方向 */
  align-items: center;

  /* 水平方向 */
  justify-content: center;
}

#重新排序

.container > .top {
  order: 1;
}

.container > .bottom {
  order: 2;
}

#移动端布局

.container {
  display: flex;
  flex-direction: column;
}

.container > .top {
  flex: 0 0 100px;
}

.container > .content {
  flex: 1 0 auto;
}

固定高度的顶部栏和动态高度的内容区域。

#类表格布局

.container {
  display: flex;
}

/* 此处的 'px' 值仅为建议百分比 */
.container > .checkbox {
  flex: 1 0 20px;
}
.container > .subject {
  flex: 1 0 400px;
}
.container > .date {
  flex: 1 0 120px;
}

创建不同宽度的列,但根据实际情况自适应大小。

#垂直对齐

.container {
  align-items: center;
}

所有子项垂直居中。

#左右对齐

.menu > .left {
  align-self: flex-start;
}
.menu > .right {
  align-self: flex-end;
}

#CSS Grid 网格布局

#Grid 模板列

#grid-container {
  display: grid;
  width: 100px;
  grid-template-columns: 20px 20% 60%;
}

#fr 相对单位

.grid {
  display: grid;
  width: 100px;
  grid-template-columns: 1fr 60px 1fr;
}

#Grid 间距

/* 行间距 20px */
/* 列间距 10px */
#grid-container {
  display: grid;
  grid-gap: 20px 10px;
}

#CSS 块级 Grid

#grid-container {
  display: block;
}

#网格行 (CSS grid-row)

CSS 语法说明:

  • grid-row: grid-row-start / grid-row-end;

示例

.item {
  grid-row: 1 / span 2;
}

#CSS 行内 Grid

#grid-container {
  display: inline-grid;
}

#minmax() 函数

.grid {
  display: grid;
  grid-template-columns: 100px minmax(100px, 500px) 100px;
}

#网格行起止 (grid-row-start & grid-row-end)

CSS 语法说明:

  • grid-row-start: auto|row-line;
  • grid-row-end: auto|row-line|span n;

示例

grid-row-start: 2;
grid-row-end: span 2;

#网格行间距 (CSS grid-row-gap)

grid-row-gap: length;

任何合法的长度值,如 px 或 %。0 为默认值

#网格区域 (CSS grid-area)

.item1 {
  grid-area: 2 / 1 / span 2 / span 3;
}

#对齐项目 (Justify Items)

#container {
  display: grid;
  justify-items: center;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 10px;
}

#网格区域模板 (CSS grid-template-areas)

.item {
  grid-area: nav;
}
.grid-container {
  display: grid;
  grid-template-areas:
    'nav nav . .'
    'nav nav . .';
}

#自身对齐 (Justify Self)

#grid-container {
  display: grid;
  justify-items: start;
}

.grid-items {
  justify-self: end;
}

网格项目被定位到行的右侧(end)。

#垂直对齐项目 (Align Items)

#container {
  display: grid;
  align-items: start;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 10px;
}

#CSS 动态内容

#变量

定义 CSS 变量

:root {
  --first-color: #16f;
  --second-color: #ff7;
}

使用变量

#firstParagraph {
  background-color: var(--first-color);
  color: var(--second-color);
}

另见: CSS 变量

#计数器

/* 将 "my-counter" 设置为 0 */
counter-set: my-counter;
/* 将 "my-counter" 递增 1 */
counter-increment: my-counter;
/* 将 "my-counter" 递减 1 */
counter-increment: my-counter -1;
/* 将 "my-counter" 重置为 0 */
counter-reset: my-counter;

另见: 计数器 counter-set

#使用计数器

body {
  counter-reset: section;
}

h3::before {
  counter-increment: section;
  content: 'Section.' counter(section);
}
ol {
  counter-reset: section;
  list-marker-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section, '.') ' ';
}

#CSS 3 技巧

#平滑滚动

html {
  scroll-behavior: smooth;
}

点击这里,页面将平滑滚动到入门指引部分

#现代 CSS

#容器查询 (尺寸)

.element-wrap {
  container: element / inline-size;
}
@container element (min-inline-size: 300px) {
  .element {
    display: flex;
    gap: 1rem;
  }
}

#容器查询 (样式)

.container {
  --variant: 1;

  &.variant2 {
    --variant: 2;
  }
}

@container style(--variant: 1) {
  button {
  } /* 不能给 .container 添加样式,但可以选择其内部元素 */
  .other-things {
  }
}

@container style(--variant: 2) {
  button {
  }
  .whatever {
  }
}

#容器单位

  • cqw(容器查询宽度)
  • cqh(容器查询高度)
  • cqi(容器查询行内方向)
  • cqb(容器查询块方向)
  • cqmin(cqi 和 cqb 中较小的)
  • cqmax(cqi 和 cqb 中较大的)
.card {
  padding: 5cqi;
  font-size: 4cqi;
  border: 1cqi solid brown;
  height: 100%;
}

h2 {
  font-size: 10cqi;
  margin-block: 0 3cqi;
}

#:has() 伪选择器

figure:has(figcaption) {
  border: 1px solid black;
  padding: 0.5rem;
}

#嵌套

.cards {
  .card {
    & .card-description {
      color: blue;
    }
    & .card-title {
      color: red;
    }
  }
}

#

#作用域

@scope {
  :scope {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    padding: 1rem;
    border: 1px solid black;
  }
  .card {
    padding: 1rem;
    border: 1px solid black;
    background: lightgray;
    h2 {
      margin: 0 0 1rem 0;
    }
  }
}

#级联层

/* 指定级联中样式的应用顺序 */
@layer legacyCard, newCard;

/* 假设你有很多样式 */
@layer newCard {
  .card {
    background-color: red;
  }
}
@layer legacyCard {
  .card {
    background-color: green;
  }
}

#逻辑属性

button {
  background-color: #4caf50;
  border: none;
  color: white;
  padding: 0.5rem 1.5rem;
  text-decoration: none;
  font: inherit;
  border-radius: 4px;
  .icon {
    position: relative;
    top: 0.125em;
    fill: white;
    width: 1em;
    aspect-ratio: 1;
    margin-inline-end: 0.25rem;
  }
}

#P3 色域

<div class="container">
  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-color: color(display-p3 1 0.5 0);
        }
      }
    </style>
  </div>
  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-color: oklch(61.88% 0.286 342.4);
        }
      }
    </style>
  </div>
  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-color: oklab(0.73 0.15 0.16);
        }
      }
    </style>
  </div>

  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-image: linear-gradient(to right in oklch, red, blue);
        }
      }
    </style>
  </div>

  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-image: linear-gradient(to right in oklab, red, blue);
        }
      }
    </style>
  </div>

  <div class="swatch">
    <style contenteditable>
      @scope {
        :scope {
          background-image: linear-gradient(to right in srgb, red, blue);
        }
      }
    </style>
  </div>
</div>

#颜色混合

.swatch {
  color: white;
  width: 100px;
  aspect-ratio: 1;
  display: grid;
  place-items: center;
  text-align: center;

  &:nth-child(1) {
    background-color: var(--bg);
  }
  &:nth-child(2) {
    background-color: color-mix(in oklch, var(--bg), black 30%);
  }
  &:nth-child(3) {
    background-color: color-mix(in oklch, var(--bg), white 30%);
  }
}

#外边距裁剪

.container {
  /* 防止元素末尾的"多余"外边距 */
  margin-trim: block-end;

  /* 类似这样的元素可能会导致问题,但也可能是其他元素 */
  > p {
    margin-block-end: 1rem;
  }
}

#文本换行

.balance {
  text-wrap: balance;
}
.pretty {
  text-wrap: pretty;
}

html {
  font-family: system-ui, sans-serif;
}

main {
  max-inline-size: 60ch;
  margin-inline: auto;
}

#子网格

.grid {
  display: grid;
  grid-template-columns: repeat(9, 1fr);
  grid-template-rows: repeat(4, minmax(100px, auto));
}

.item {
  display: grid;
  grid-column: 2 / 7;
  grid-row: 2 / 4;
  grid-template-columns: subgrid;
  grid-template-rows: repeat(3, 80px);
}

.subitem {
  grid-column: 3 / 6;
  grid-row: 1 / 3;
}