这是一份关于 CSS 优点的快速参考备忘单,列出了选择器语法、属性、单位和其他有用的信息
如有疑问和建议,欢迎与本人交流沟通,也可以关注公众号:CTO Plus
CSS 功能丰富,不仅仅是布局页面
一、CSS 基础概念
1.1 CSS 简介
CSS (Cascading Style Sheets) 层叠样式表,是一种样式表语言,用于描述HTML或XML文档的呈现方式。CSS 解决了内容与表现分离的问题,使网页设计更加灵活和易于维护。
1.2 CSS 语法结构
selector {
property: value;
/* 注释 */
}
- 选择器(selector):指定要样式化的HTML元素
- 属性(property):要设置的样式特征
- 值(value):属性的具体设置
- 声明块:由花括号包围的一组声明
1.3 CSS 引入方式
-
内联样式:直接写在HTML元素的style属性中
<p style="color: red;">文本</p>
内部样式表:写在HTML文档的<head>部分的<style>标签内
<head>
<style>
p { color: blue; }
</style>
</head>
外部样式表:单独的.css文件,通过<link>引入
<head>
<link rel="stylesheet" href="styles.css">
</head>
@import方式:在CSS文件中导入其他CSS文件
@import url('other-styles.css');
二、CSS 选择器大全
2.1 基本选择器
- 元素选择器:
p { } - 类选择器:
.class { } - ID选择器:
#id { } - 通配选择器:
* { }
2.2 组合选择器
- 后代选择器:
div p { } - 子元素选择器:
div > p { } - 相邻兄弟选择器:
h1 + p { } - 通用兄弟选择器:
h1 ~ p { }
2.3 属性选择器
[attr]:具有attr属性的元素[attr=value]:attr属性等于value的元素[attr~=value]:attr属性包含value单词的元素[attr|=value]:attr属性以value开头或value-开头的元素[attr^=value]:attr属性以value开头的元素[attr$=value]:attr属性以value结尾的元素[attr*=value]:attr属性包含value子串的元素
2.4 伪类选择器
-
链接相关:
:link:未访问的链接:visited:已访问的链接:hover:鼠标悬停:active:激活状态:focus:获得焦点
-
结构伪类:
:first-child:第一个子元素:last-child:最后一个子元素:nth-child(n):第n个子元素:nth-last-child(n):倒数第n个子元素:first-of-type:同类型的第一个:last-of-type:同类型的最后一个:nth-of-type(n):同类型的第n个:nth-last-of-type(n):同类型的倒数第n个:only-child:唯一子元素:only-of-type:同类型的唯一元素:empty:没有子元素的元素
-
表单相关:
:checked:被选中的表单元素:disabled:禁用的表单元素:enabled:启用的表单元素:required:必填的表单元素:optional:可选的表单元素:valid:有效输入:invalid:无效输入:in-range:在范围内的输入:out-of-range:超出范围的输入:read-only:只读元素:read-write:可读写元素
-
其他伪类:
:root:文档根元素:target:当前活动的目标元素:not(selector):不匹配选择器的元素:lang(language):指定语言的元素
2.5 伪元素选择器
::before:在元素前插入内容::after:在元素后插入内容::first-letter:首字母::first-line:首行::selection:用户选中的部分::placeholder:输入框的占位文本
三、CSS 属性大全
3.1 文本属性
color:文本颜色font-family:字体font-size:字体大小font-weight:字体粗细 (normal, bold, 100-900)font-style:字体样式 (normal, italic, oblique)font-variant:小型大写字母 (normal, small-caps)line-height:行高text-align:文本对齐 (left, right, center, justify)text-decoration:文本装饰 (none, underline, overline, line-through)text-transform:文本转换 (none, capitalize, uppercase, lowercase)text-indent:首行缩进letter-spacing:字符间距word-spacing:单词间距white-space:空白处理 (normal, nowrap, pre, pre-wrap, pre-line)text-overflow:文本溢出 (clip, ellipsis)text-shadow:文本阴影 (h-shadow v-shadow blur color)direction:文本方向 (ltr, rtl)unicode-bidi:双向文本算法
3.2 背景属性
background-color:背景颜色background-image:背景图片background-repeat:背景重复 (repeat, repeat-x, repeat-y, no-repeat)background-position:背景位置 (left/center/right top/center/bottom)background-attachment:背景附着 (scroll, fixed, local)background-size:背景尺寸 (auto, cover, contain, 长度/百分比)background-clip:背景绘制区域 (border-box, padding-box, content-box)background-origin:背景定位区域 (border-box, padding-box, content-box)background:简写属性
3.3 边框属性
border-width:边框宽度border-style:边框样式 (none, hidden, dotted, dashed, solid, double, groove, ridge, inset, outset)border-color:边框颜色border:简写属性 (width style color)border-radius:边框圆角border-image:边框图片border-image-source:边框图片源border-image-slice:边框图片切片border-image-width:边框图片宽度border-image-outset:边框图片外延border-image-repeat:边框图片重复 (stretch, repeat, round)box-shadow:盒子阴影 (h-shadow v-shadow blur spread color inset)
3.4 盒模型属性
width:宽度height:高度min-width:最小宽度min-height:最小高度max-width:最大宽度max-height:最大高度margin:外边距margin-top:上外边距margin-right:右外边距margin-bottom:下外边距margin-left:左外边距padding:内边距padding-top:上内边距padding-right:右内边距padding-bottom:下内边距padding-left:左内边距box-sizing:盒模型计算方式 (content-box, border-box)
3.5 布局属性
display:显示方式 (block, inline, inline-block, flex, grid, none等)position:定位方式 (static, relative, absolute, fixed, sticky)top:定位上偏移right:定位右偏移bottom:定位下偏移left:定位左偏移float:浮动 (left, right, none)clear:清除浮动 (left, right, both, none)z-index:堆叠顺序overflow:溢出处理 (visible, hidden, scroll, auto)overflow-x:水平溢出处理overflow-y:垂直溢出处理visibility:可见性 (visible, hidden, collapse)clip:裁剪 (rect(top, right, bottom, left))clip-path:裁剪路径
3.6 Flexbox 弹性布局
flex-direction:主轴方向 (row, row-reverse, column, column-reverse)flex-wrap:换行方式 (nowrap, wrap, wrap-reverse)flex-flow:flex-direction和flex-wrap的简写justify-content:主轴对齐方式 (flex-start, flex-end, center, space-between, space-around, space-evenly)align-items:交叉轴对齐方式 (flex-start, flex-end, center, baseline, stretch)align-content:多行对齐方式 (flex-start, flex-end, center, space-between, space-around, stretch)order:项目排序flex-grow:放大比例flex-shrink:缩小比例flex-basis:项目初始大小flex:flex-grow, flex-shrink和flex-basis的简写align-self:单个项目对齐方式 (auto, flex-start, flex-end, center, baseline, stretch)
3.7 Grid 网格布局
grid-template-columns:定义列grid-template-rows:定义行grid-template-areas:定义区域grid-template:grid-template-rows, grid-template-columns和grid-template-areas的简写grid-column-gap:列间距grid-row-gap:行间距grid-gap:grid-row-gap和grid-column-gap的简写justify-items:单元格水平对齐 (start, end, center, stretch)align-items:单元格垂直对齐 (start, end, center, stretch)place-items:align-items和justify-items的简写justify-content:网格水平对齐 (start, end, center, stretch, space-around, space-between, space-evenly)align-content:网格垂直对齐 (start, end, center, stretch, space-around, space-between, space-evenly)place-content:align-content和justify-content的简写grid-auto-columns:隐式创建的列大小grid-auto-rows:隐式创建的行大小grid-auto-flow:自动布局算法 (row, column, dense)grid:grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns和grid-auto-flow的简写grid-column-start:项目起始列线grid-column-end:项目结束列线grid-row-start:项目起始行线grid-row-end:项目结束行线grid-column:grid-column-start和grid-column-end的简写grid-row:grid-row-start和grid-row-end的简写grid-area:grid-row-start, grid-column-start, grid-row-end和grid-column-end的简写或区域名称justify-self:单个项目水平对齐 (start, end, center, stretch)align-self:单个项目垂直对齐 (start, end, center, stretch)place-self:align-self和justify-self的简写
3.8 过渡与动画
过渡属性
transition-property:过渡属性 (all, none, property)transition-duration:过渡持续时间transition-timing-function:过渡时间函数 (ease, linear, ease-in, ease-out, ease-in-out, cubic-bezier(n,n,n,n))transition-delay:过渡延迟transition:简写属性
动画属性
animation-name:动画名称animation-duration:动画持续时间animation-timing-function:动画时间函数animation-delay:动画延迟animation-iteration-count:动画播放次数 (infinite, number)animation-direction:动画方向 (normal, reverse, alternate, alternate-reverse)animation-fill-mode:动画填充模式 (none, forwards, backwards, both)animation-play-state:动画播放状态 (running, paused)animation:简写属性
关键帧规则
@keyframes animation-name {
from { /* 起始状态 */ }
to { /* 结束状态 */ }
/* 或 */
0% { /* 状态 */ }
50% { /* 状态 */ }
100% { /* 状态 */ }
}
3.9 变换属性
transform:变换函数 (none, matrix(), translate(), scale(), rotate(), skew())transform-origin:变换原点transform-style:变换样式 (flat, preserve-3d)perspective:透视距离perspective-origin:透视原点backface-visibility:背面可见性 (visible, hidden)
3.10 多列布局
column-count:列数column-width:列宽columns:column-count和column-width的简写column-gap:列间距column-rule:列间规则线column-rule-width:规则线宽度column-rule-style:规则线样式column-rule-color:规则线颜色column-span:跨列 (none, all)column-fill:列填充方式 (auto, balance)
3.11 用户界面属性
resize:调整大小 (none, both, horizontal, vertical)cursor:光标类型 (auto, default, pointer, text, move等)outline:轮廓outline-width:轮廓宽度outline-style:轮廓样式outline-color:轮廓颜色outline-offset:轮廓偏移appearance:外观 (none, normal等)box-decoration-break:盒装饰中断 (slice, clone)caret-color:插入符号颜色
3.12 滤镜效果
filter:滤镜 (none, blur(), brightness(), contrast(), drop-shadow(), grayscale(), hue-rotate(), invert(), opacity(), saturate(), sepia(), url())backdrop-filter:背景滤镜mix-blend-mode:混合模式 (normal, multiply, screen, overlay等)background-blend-mode:背景混合模式
3.13 变量与自定义属性
:root {
--main-color: #06c;
}
.element {
color: var(--main-color);
}
3.14 其他属性
all:重置所有属性 (initial, inherit, unset, revert)will-change:提示浏览器哪些属性会变化contain:限制样式计算范围isolation:隔离混合模式pointer-events:指针事件 (auto, none)scroll-behavior:滚动行为 (auto, smooth)touch-action:触摸操作 (auto, none, pan-x, pan-y等)
四、CSS 单位大全
4.1 绝对单位
px:像素cm:厘米mm:毫米in:英寸 (1in = 96px = 2.54cm)pt:点 (1pt = 1/72in)pc:派卡 (1pc = 12pt)
4.2 相对单位
em:相对于当前元素的字体大小rem:相对于根元素的字体大小%:相对于父元素的百分比vw:视口宽度的1%vh:视口高度的1%vmin:视口较小尺寸的1%vmax:视口较大尺寸的1%ex:相对于当前字体的x高度ch:相对于"0"字符的宽度fr:网格布局中的分数单位
4.3 角度单位
deg:度grad:梯度 (100grad = 90deg)rad:弧度turn:圈 (1turn = 360deg)
4.4 时间单位
s:秒ms:毫秒 (1s = 1000ms)
4.5 频率单位
Hz:赫兹kHz:千赫兹 (1kHz = 1000Hz)
4.6 分辨率单位
dpi:每英寸点数dpcm:每厘米点数dppx:每像素点数 (1dppx = 96dpi)
五、CSS 函数大全
5.1 颜色函数
rgb()/rgba()hsl()/hsla()hwb()lab()lch()color()color-mix()color-contrast()
5.2 数学函数
calc()min()max()clamp()
5.3 形状函数
circle()ellipse()inset()polygon()path()
5.4 变换函数
matrix()matrix3d()perspective()rotate()rotate3d()rotateX()rotateY()rotateZ()scale()scale3d()scaleX()scaleY()scaleZ()skew()skewX()skewY()translate()translate3d()translateX()translateY()translateZ()
5.5 渐变函数
linear-gradient()radial-gradient()conic-gradient()repeating-linear-gradient()repeating-radial-gradient()repeating-conic-gradient()
5.6 滤镜函数
blur()brightness()contrast()drop-shadow()grayscale()hue-rotate()invert()opacity()saturate()sepia()url()
5.7 其他函数
attr()var()counter()counters()image()element()cross-fade()symbols()env()format()local()target-counter()target-counters()target-text()
六、CSS 媒体查询
6.1 媒体类型
all:所有设备print:打印机screen:屏幕speech:语音合成器
6.2 媒体特性
视口/页面特性
width/min-width/max-widthheight/min-height/max-heightaspect-ratio/min-aspect-ratio/max-aspect-ratioorientation:方向 (portrait, landscape)
显示质量
resolution/min-resolution/max-resolutionscan:扫描方式 (interlace, progressive)grid:是否基于网格的设备update:更新频率 (none, slow, fast)
颜色
color/min-color/max-colorcolor-index/min-color-index/max-color-indexmonochrome/min-monochrome/max-monochromecolor-gamut:色域 (srgb, p3, rec2020)
交互
hover:悬停能力 (none, hover)pointer:指针精度 (none, coarse, fine)any-pointer:任意输入设备的指针精度any-hover:任意输入设备的悬停能力
6.3 逻辑操作符
and:与,:或not:非only:仅
6.4 示例
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* 样式 */
}
@media (hover: hover) and (pointer: fine) {
/* 样式 */
}
@media (prefers-color-scheme: dark) {
/* 暗色模式样式 */
}
@media (prefers-reduced-motion: reduce) {
/* 减少动画的样式 */
}
七、CSS 预处理器特性
7.1 变量
$primary-color: #333;
body {
color: $primary-color;
}
7.2 嵌套
nav {
ul {
margin: 0;
li {
display: inline-block;
}
}
}
7.3 混合(Mixins)
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
.box { @include border-radius(10px); }
7.4 继承/扩展
.message {
border: 1px solid #ccc;
padding: 10px;
}
.success {
@extend .message;
border-color: green;
}
7.5 运算
.container {
width: 100% - 30px;
}
7.6 函数
@function calculate-width($col-span) {
@return 100% / $col-span;
}
.span-4 {
width: calculate-width(4);
}
7.7 条件与循环
@if lightness($color) > 30% {
background-color: #000;
} @else {
background-color: #fff;
}
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
@each $animal in puma, sea-slug, egret {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
7.8 导入
@import "reset";
@import "variables";
@import "mixins";
八、CSS 最佳实践
8.1 组织CSS代码
- 遵循一致的命名约定:如BEM (Block__Element--Modifier)
- 模块化CSS:按功能/组件组织代码
- 注释结构:
/* ======================
Header Styles
====================== */
8.2 性能优化
- 减少选择器复杂性:避免深层嵌套
- 避免通配选择器:
* - 减少重绘和回流:慎用影响布局的属性
- 使用硬件加速:
transform和opacity - 压缩CSS文件:移除空格注释
- 关键CSS:首屏样式内联
- 使用CSS精灵图:减少HTTP请求
8.3 可维护性
- 使用CSS变量:方便主题切换
- 避免!important:除非必要
- 响应式设计:移动优先
- 渐进增强:基础样式先于高级特性
- 浏览器前缀处理:使用Autoprefixer
8.4 常见问题解决方案
- 清除浮动:
.clearfix::after {
content: "";
display: table;
clear: both;
}
/* Flexbox方式 */
.container {
display: flex;
align-items: center;
justify-content: center;
}
/* Grid方式 */
.container {
display: grid;
place-items: center;
}
/* 绝对定位方式 */
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Flexbox方式 */
.container {
display: flex;
}
/* Grid方式 */
.container {
display: grid;
grid-auto-flow: column;
align-items: stretch;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content {
flex: 1;
}
九、CSS 未来特性
9.1 容器查询
@container (min-width: 700px) {
.card {
/* 样式 */
}
}
9.2 层叠层(@layer)
@layer base, theme, utilities;
@layer base {
/* 基础样式 */
}
@layer theme {
/* 主题样式 */
}
@layer utilities {
/* 工具类 */
}
9.3 作用域样式(@scope)
@scope (.card) to (.card-content) {
:scope {
/* 作用域样式 */
}
}
9.4 颜色函数
oklab()/oklch()color-mix()color-contrast()
9.5 其他新兴特性
- 子网格:
subgrid :has()选择器:父选择器:focus-visible:键盘焦点样式:user-invalid:用户无效输入:modal:模态对话框- 视图过渡API:
view-transition - 滚动时间线:
scroll-timeline
十、CSS 资源推荐
10.1 学习资源
- MDN CSS 文档
- CSS Tricks
- Can I Use (兼容性查询)
- CSS规范 (W3C)
- Codepen (代码示例)
10.2 工具
- Autoprefixer
- PostCSS
- Sass/Less/Stylus
- PurgeCSS
- CSS Minifiers
10.3 框架
- Bootstrap
- Tailwind CSS
- Bulma
- Foundation
- Materialize
10.4 验证工具
- W3C CSS验证器
- Lighthouse (性能测试)
这份CSS速查手册涵盖了从基础到高级的几乎所有CSS知识点,可以作为日常开发的参考指南。随着CSS标准的不断发展,建议定期关注新特性的引入和浏览器支持情况。