CSS高级特性
CSS变量
CSS变量(也称为自定义属性)允许开发者定义可重用的值,使样式表更加灵活和可维护。
基本用法
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size-base: 16px;
--spacing-unit: 8px;
}
.button {
background-color: var(--primary-color);
padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
font-size: var(--font-size-base);
color: white;
border: none;
border-radius: 4px;
}
.button.secondary {
background-color: var(--secondary-color);
}
变量作用域
CSS变量遵循级联规则,可以在不同的选择器中重新定义:
:root {
--text-color: black;
}
.dark-theme {
--text-color: white;
}
p {
color: var(--text-color);
}
回退值
可以为变量提供回退值,当变量未定义或值无效时使用:
.element {
/* 如果--padding未定义,则使用10px */
padding: var(--padding, 10px);
}
使用JavaScript操作CSS变量
// 获取CSS变量值
const rootStyles = getComputedStyle(document.documentElement);
const primaryColor = rootStyles.getPropertyValue('--primary-color').trim();
console.log(primaryColor); // #3498db
// 设置CSS变量值
document.documentElement.style.setProperty('--primary-color', '#ff0000');
实际应用示例
主题切换
<div class="theme-container">
<button id="light-theme">浅色主题</button>
<button id="dark-theme">深色主题</button>
</div>
<div class="content">
<h1>CSS变量示例</h1>
<p>这是一个使用CSS变量实现主题切换的示例。</p>
</div>
:root {
--bg-color: #ffffff;
--text-color: #333333;
--heading-color: #222222;
--border-color: #dddddd;
}
.dark-theme {
--bg-color: #222222;
--text-color: #f0f0f0;
--heading-color: #ffffff;
--border-color: #444444;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
h1 {
color: var(--heading-color);
}
.content {
border: 1px solid var(--border-color);
padding: 20px;
border-radius: 8px;
}
document.getElementById('light-theme').addEventListener('click', function() {
document.documentElement.classList.remove('dark-theme');
});
document.getElementById('dark-theme').addEventListener('click', function() {
document.documentElement.classList.add('dark-theme');
});
CSS函数
CSS提供了多种函数,用于执行计算、转换颜色、创建渐变等操作。
calc()函数
calc()函数允许在CSS中执行数学计算,甚至可以混合不同的单位:
.container {
/* 100%宽度减去40px的内边距 */
width: calc(100% - 40px);
/* 混合不同单位 */
margin-top: calc(2em + 20px);
/* 复杂计算 */
height: calc(100vh - 80px - 2em);
}
min()、max()和clamp()函数
这些函数用于在一组值中选择最小值、最大值或将值限制在一个范围内:
.responsive-text {
/* 选择16px和3vw中的较小值 */
font-size: min(16px, 3vw);
/* 选择18px和4vw中的较大值 */
line-height: max(18px, 4vw);
/* 将宽度限制在200px到800px之间,首选值为90% */
width: clamp(200px, 90%, 800px);
}
颜色函数
CSS提供了多种处理颜色的函数:
.element {
/* RGB和RGBA */
color: rgb(255, 0, 0);
background-color: rgba(0, 0, 255, 0.5);
/* HSL和HSLA */
border-color: hsl(120, 100%, 50%);
box-shadow: 0010pxhsla(0, 100%, 50%, 0.7);
/* 现代颜色函数(CSS Color Module Level 4) */
color: rgb(25500 / 0.8); /* 空格分隔,透明度用斜杠 */
/* 颜色混合(实验性) */
color: color-mix(in srgb, #ff0000, #0000ff50%);
}
自定义属性函数env()和var()
.safe-area-aware {
/* 使用环境变量(主要用于适应设备安全区域) */
padding-top: env(safe-area-inset-top, 20px);
padding-bottom: env(safe-area-inset-bottom, 20px);
/* 使用CSS变量 */
margin: var(--spacing, 10px);
}
滤镜和混合模式
滤镜(filter)
filter属性允许对元素应用图形效果,如模糊、亮度调整、对比度等:
filter: <filter-function> [<filter-function> ...];
/* ========= CSS filter 语法速查 ========= */
/* 基础模板 */
selector {
filter: <filter-function> [<filter-function> ...];
}
/* ① 模糊 */
blur(radius) /* radius ≥ 0,px/em/vw 均可 */
/* ② 灰度 */
grayscale( amount ) /* 0% = 原图,100% = 完全黑白 */
/* ③ 棕褐/老照片 */
sepia( amount ) /* 0% - 100% */
/* ④ 亮度 */
brightness( ratio ) /* 1 = 原图;>1 更亮;<1 更暗;0 = 全黑 */
/* ⑤ 对比度 */
contrast( ratio ) /* 1 = 原图;0 = 灰色;>1 高反差 */
/* ⑥ 色相旋转 */
hue-rotate( angle ) /* deg / rad / turn,一圈 360deg */
/* ⑦ 反相 */
invert( amount ) /* 0% = 原图,100% = 底片 */
/* ⑧ 透明度(不影响子元素) */
opacity( amount ) /* 0% - 100%,语义同 CSS opacity */
/* ⑨ 饱和度 */
saturate( ratio ) /* 1 = 原图;0 = 灰度;>1 更鲜艳 */
/* ⑩ 投影(比 box-shadow 更贴合透明像素) */
drop-shadow( offset-x offset-y blur-radius color )
/* ⑪ 组合写法(顺序执行,空格分隔) */
filter: contrast(150%) brightness(120%) sepia(30%);
/* ⑫ 多重同函数(霓虹辉光) */
filter:
drop-shadow(0 0 4px #f0f)
drop-shadow(0 0 8px #fff);
/* ⑬ 取消所有滤镜 */
filter: none;
/* ========= 滤镜大合集:每行上面单独备注 ========= */
/* 高斯模糊:半径越大越糊,常用于背景虚化 */
.blur-effect {
filter: blur(5px);
}
/* 灰度:100% = 完全黑白,0% = 原图;可做“黑白切换”主题 */
.grayscale-effect {
filter: grayscale(100%);
}
/* 复古棕褐:70% 强度让照片看起来像老胶片 */
.sepia-effect {
filter: sepia(70%);
}
/* 亮度提升:150% 比原图亮 1.5 倍;<100% 会变暗 */
.brightness-effect {
filter: brightness(150%);
}
/* 对比度:200% 色彩反差更强;0% 会变成一片灰 */
.contrast-effect {
filter: contrast(200%);
}
/* 色相旋转:90deg 把色轮转动 90°,红变绿、绿变紫…… */
.hue-rotate-effect {
filter: hue-rotate(90deg);
}
/* 完全反相:100% 得到“底片”效果;0% 保持原样 */
.invert-effect {
filter: invert(100%);
}
/* 透明度:50% 半透明;与 CSS opacity 区别是**不会**影响子元素 */
.opacity-effect {
filter: opacity(50%);
}
/* 饱和度:200% 色彩加倍鲜艳;0% 变成灰度图 */
.saturate-effect {
filter: saturate(200%);
}
/* 投影滤镜:比 box-shadow 更真实,会贴着透明像素边缘 */
.shadow-effect {
filter: drop-shadow(5px 5px 10px rgba(0, 0, 0, 0.5));
}
/* 组合滤镜:一次写多个,顺序从左到右执行,先对比→再亮度→再复古 */
.combined-effect {
filter: contrast(150%) brightness(120%) sepia(30%);
}
/* 锐化:使边缘更清晰,数值越大越锐;0 为原图 */
.sharp-effect {
filter: contrast(150%) saturate(120%);
/* 目前无原生 sharp(),用“高对比+高饱和”模拟 */
}
/* 褪色(降低饱和)(0% = 灰度,50% = 半饱和) */
.desaturate-effect {
filter: saturate(50%);
}
/* 伽马校正:>1 图像变亮,<1 变暗;1 为原图 */
.gamma-effect {
filter: brightness(1.2) contrast(0.9);
/* 暂无 gamma(),用 brightness+contrast 近似 */
}
/* 褪色旧电影(快速做旧) */
.old-movie-effect {
filter: sepia(30%) contrast(160%) brightness(90%) saturate(80%);
}
/* 极冷色调(色轮+240°) */
.cold-tone-effect {
filter: hue-rotate(240deg) saturate(120%);
}
/* 极暖色调(色轮-60°) */
.warm-tone-effect {
filter: hue-rotate(-60deg) saturate(130%);
}
/* 高反差黑白(艺术剪影) */
.high-contrast-bw {
filter: grayscale(100%) contrast(200%);
}
/* 反转 + 色相旋转(赛博朋克风) */
.cyber-effect {
filter: invert(1) hue-rotate(180deg) saturate(150%);
}
/* 褪色 + 亮度提升(INS 轻复古) */
.ins-effect {
filter: sepia(15%) brightness(110%) contrast(90%) saturate(95%);
}
/* 多重投影(可叠加多层光晕) */
.multi-glow {
filter:
drop-shadow(0 0 4px #ff00ff)
drop-shadow(0 0 8px #00ffff);
/* 顺序执行,先粉再青,形成霓虹边缘 */
}
背景混合模式
background-blend-mode属性定义了元素的背景图片和背景颜色如何混合:
.blend-multiply {
background-image: url('pattern.png');
background-color: #3498db;
background-blend-mode: multiply;
}
.blend-screen {
background-image: url('texture.jpg');
background-color: #e74c3c;
background-blend-mode: screen;
}
.blend-overlay {
background-image: url('image.jpg');
background-color: #2ecc71;
background-blend-mode: overlay;
}
混合模式
mix-blend-mode属性定义了元素的内容应该如何与父元素的内容和背景混合:
.text-blend {
mix-blend-mode: difference;
color: white;
}
.image-blend {
mix-blend-mode: multiply;
}
.element-blend {
mix-blend-mode: overlay;
}
实际应用示例
图片滤镜画廊
<div class="filter-gallery">
<div class="filter-controls">
<button data-filter="none">原图</button>
<button data-filter="grayscale">灰度</button>
<button data-filter="sepia">复古</button>
<button data-filter="blur">模糊</button>
<button data-filter="custom">自定义</button>
</div>
<div class="image-container">
<img src="sample-image.jpg" id="filter-target" alt="滤镜示例图片">
</div>
</div>
/* ===== .filter-gallery 容器 ===== */
/* 限制总宽并居中,保证大图也不撑破视口 */
.filter-gallery {
max-width: 800px;
margin: 0 auto;
}
/* ===== .filter-controls 控制栏 ===== */
/* Flex 横向排列按钮,间隙 10px,底部留 20px 间距 */
.filter-controls {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
/* ===== .image-container 图片外壳 ===== */
/* 隐藏溢出部分 + 圆角,让图片圆角生效 */
.image-container {
overflow: hidden;
border-radius: 8px;
}
/* ===== #filter-target 图片本体 ===== */
/* 宽度 100% 自适应容器,块级显示,滤镜变化带 0.3s 过渡 */
#filter-target {
width: 100%;
display: block;
transition: filter 0.3s ease;
}
/* ===== 各类滤镜状态 ===== */
/* 灰度:完全黑白 */
#filter-target.grayscale {
filter: grayscale(100%);
}
/* 复古棕褐:80% 强度 */
#filter-target.sepia {
filter: sepia(80%);
}
/* 高斯模糊:5px 半径 */
#filter-target.blur {
filter: blur(5px);
}
/* 自定义组合:高对比 + 色相旋转45° + 轻微提亮 */
#filter-target.custom {
filter: contrast(150%) hue-rotate(45deg) brightness(110%);
}
document.querySelectorAll('.filter-controls button').forEach(button => {
button.addEventListener('click', function() {
const filter = this.getAttribute('data-filter');
const image = document.getElementById('filter-target');
// 移除所有滤镜类
image.className = '';
// 添加选中的滤镜类
if (filter !== 'none') {
image.classList.add(filter);
}
});
});
形状和裁剪
形状(shape-outside)
shape-outside: <basic-shape> | <image> | <box> | none;
是 CSS 浮动排版领域的“黑科技”——让文本不再紧贴着矩形浮动盒,而是沿着任意几何形状环绕。
shape-outside属性定义了一个形状,文本将围绕这个形状流动:
/* ---------- 圆形浮动区域 ---------- */
/* 画一个真圆:border-radius 50% 让视觉圆 + shape-outside circle(50%) 让文本沿圆环绕 */
.circle-shape {
float: left; /* 必须浮动,shape-outside 才生效 */
width: 200px; height: 200px; /* 正方形基础,50% 半径=100px */
border-radius: 50%; /* 视觉圆角 */
background-color: #3498db; /* 填充色 */
margin-right: 20px; /* 右侧留呼吸距离 */
shape-outside: circle(50%); /* 文本沿圆边缘流动(圆心居中,半径=50%最小边) */
}
/* ---------- 椭圆浮动区域 ---------- */
/* 真椭圆:宽度>高度,border-radius 50%/50% 视觉椭圆 + ellipse(50% 50%) 文本环绕 */
.ellipse-shape {
float: right; /* 靠右浮动,文本从左侧流入 */
width: 300px; height: 200px; /* 长轴 300px,短轴 200px */
background-color: #e74c3c; /* 填充色 */
margin-left: 20px; /* 左侧留呼吸距离 */
border-radius: 50% / 50%; /* 横向 50% 纵向 50% → 真椭圆视觉 */
shape-outside: ellipse(50% 50%); /* 椭圆环绕,两轴半径=50% 对应边长 */
}
/* ---------- 自定义多边形浮动区域 ---------- */
/* 五边形:左上角开始顺时针画点;clip-path 负责视觉,shape-outside 负责文本流 */
.polygon-shape {
float: left; /* 左浮动,右侧文本环绕 */
width: 200px; height: 200px; /* 提供坐标系 200×200 */
background-color: #2ecc71; /* 填充色 */
margin-right: 20px; /* 右侧留呼吸距离 */
/* 视觉裁剪:五边形路径(坐标顺序:左上→右上→右中→下中→左中) */
clip-path: polygon(0 0, 100% 0, 100% 75%, 50% 100%, 0 75%);
/* 文本沿相同五边形流动;路径与 clip-path 保持一致 */
shape-outside: polygon(0 0, 100% 0, 100% 75%, 50% 100%, 0 75%);
}
裁剪路径(clip-path)
clip-path属性可以创建一个裁剪区域,只显示元素的一部分:
/* ========== 基础裁剪语法示例 ========== */
/* ① 圆形裁剪:半径 40%,圆心默认元素中心 */
.clip-circle {
clip-path: circle(40%);
}
/* ② 椭圆裁剪:水平半径 50% 垂直半径 30%,圆心居中 */
.clip-ellipse {
clip-path: ellipse(50% 30% at 50% 50%);
}
/* ③ 五边形(五角星简化版)顶点坐标顺时针 */
.clip-polygon {
clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%);
}
/* ④ 内凹圆角矩形:上右下左内缩 + round 圆角 */
.clip-inset {
clip-path: inset(10% 20% 30% 10% round 20px);
}
/* ========== 动画效果 ========== */
/* 初始圆形 40%,过渡 0.5s */
.clip-animate {
clip-path: circle(40%);
transition: clip-path 0.5s ease;
}
/* hover 时扩大到 50%,产生“放大镜”效果 */
.clip-animate:hover {
clip-path: circle(50%);
}
实际应用示例
创意图片展示
<div class="creative-gallery">
<div class="gallery-item">
<img src="image1.jpg" alt="创意图片1">
<div class="overlay">图片说明</div>
</div>
<div class="gallery-item hexagon">
<img src="image2.jpg" alt="创意图片2">
<div class="overlay">图片说明</div>
</div>
<div class="gallery-item circle">
<img src="image3.jpg" alt="创意图片3">
<div class="overlay">图片说明</div>
</div>
<div class="gallery-item triangle">
<img src="image4.jpg" alt="创意图片4">
<div class="overlay">图片说明</div>
</div>
</div>
.creative-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.gallery-item {
position: relative;
overflow: hidden;
height: 300px;
border-radius: 8px;
transition: transform 0.3s ease;
}
.gallery-itemimg {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.5s ease;
}
.gallery-item:hoverimg {
transform: scale(1.1);
}
.overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px;
transform: translateY(100%);
transition: transform 0.3s ease;
}
.gallery-item:hover.overlay {
transform: translateY(0);
}
/* 形状变化 */
.hexagon {
clip-path: polygon(25%0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
}
.circle {
clip-path: circle(50% at 50%50%);
}
.triangle {
clip-path: polygon(50%0%, 0%100%, 100%100%);
}
遮罩(Mask)
遮罩允许使用图像、渐变或形状来隐藏元素的部分内容:
.mask-image {
/* 使用PNG图像作为遮罩 */
mask-image: url('mask.png');
mask-size: cover;
mask-repeat: no-repeat;
mask-position: center;
}
.mask-gradient {
/* 使用渐变作为遮罩 */
mask-image: linear-gradient(to right, transparent, black);
}
.mask-multiple {
/* 使用多个遮罩 */
mask-image: url('mask1.png'), linear-gradient(to right, black, transparent);
mask-size: 100px100px, cover;
mask-repeat: no-repeat, no-repeat;
mask-position: center, center;
mask-composite: intersect; /* 遮罩组合方式 */
}
容器查询
容器查询是一个新兴的CSS特性,允许基于父容器的大小而非视口大小来应用样式:
/* 定义一个查询容器 */
.card-container {
container-type: inline-size;
container-name: card;
}
.card {
display: grid;
grid-template-columns: 1fr;
}
/* 当容器宽度至少为400px时应用的样式 */
@container card (min-width: 400px) {
.card {
grid-template-columns: 200px1fr;
}
}
/* 当容器宽度至少为600px时应用的样式 */
@container card (min-width: 600px) {
.card {
grid-template-columns: 250px1fr;
gap: 20px;
}
}
滚动捕捉
滚动捕捉允许控制滚动结束时的停止位置,创建类似幻灯片的滚动体验:
让用户手指/鼠标滚轮“轻轻一滑”就精准停在一整屏(或一张卡片)上,避免“停在半截”的割裂感,大幅提升轮播、全屏站点、横向列表的操作体验。
/* ========= 滚动捕捉(Scroll Snap)注释版 ========= */
/* 垂直全屏滚动容器 */
.scroll-container {
scroll-snap-type: y mandatory; /* 纵向捕捉,mandatory=强制停稳才松手 */
overflow-y: scroll; /* 允许纵向滚动 */
height: 100vh; /* 一屏高度,保证每次只露一屏 */
}
/* 每一屏内容块 */
.scroll-section {
scroll-snap-align: start; /* 停稳时对齐容器顶部(start) */
height: 100vh; /* 占满一屏,保证捕捉点一致 */
display: flex; /* 以下三行居中内容 */
align-items: center;
justify-content: center;
}
/* 水平滚动捕捉示例 */
.horizontal-scroll {
scroll-snap-type: x mandatory; /* 横向捕捉,mandatory=每滑一屏必停 */
display: flex; /* 横向排列子项 */
overflow-x: scroll; /* 允许横向滚动 */
width: 100%; /* 占满父宽 */
}
/* 水平滚动中的每一项 */
.horizontal-item {
scroll-snap-align: center; /* 停稳时对齐容器中心(center) */
min-width: 100%; /* 每屏占满父宽,可改成 80% 露出边缘 */
height: 300px; /* 固定高度,方便演示 */
}
逻辑属性
逻辑属性使CSS更适应不同的书写模式和阅读方向:
.element {
/* 传统物理属性 */
margin-left: 10px;
margin-right: 20px;
padding-top: 15px;
padding-bottom: 15px;
border-left: 1px solid black;
/* 逻辑属性 */
margin-inline-start: 10px; /* 行内开始方向的外边距 */
margin-inline-end: 20px; /* 行内结束方向的外边距 */
padding-block-start: 15px; /* 块级开始方向的内边距 */
padding-block-end: 15px; /* 块级结束方向的内边距 */
border-inline-start: 1px solid black; /* 行内开始方向的边框 */
/* 简写形式 */
margin-inline: 10px20px; /* 开始 结束 */
padding-block: 15px; /* 开始和结束相同 */
/* 尺寸 */
inline-size: 200px; /* 行内方向的尺寸(通常是宽度) */
block-size: 100px; /* 块级方向的尺寸(通常是高度) */
}
支持查询
支持查询允许检测浏览器是否支持特定的CSS特性:
/* 检查是否支持网格布局 */
@supports (display: grid) {
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
}
/* 检查是否支持粘性定位 */
@supports (position: sticky) {
.header {
position: sticky;
top: 0;
z-index: 100;
}
}
/* 逻辑运算符 */
@supports (display: grid) and (gap: 20px) {
/* 同时支持网格和间隙属性 */
}
@supports (display: flex) or (display: grid) {
/* 支持弹性盒或网格布局 */
}
@supportsnot (display: grid) {
/* 不支持网格布局 */
}
自定义光标
.custom-cursor {
/* 使用自定义图像作为光标 */
cursor: url('custom-cursor.png'), auto;
/* 指定热点位置 */
cursor: url('custom-cursor.png') 1010, auto;
}
/* 内置光标类型 */
.cursor-types {
cursor: pointer; /* 手型光标,表示链接 */
cursor: grab; /* 抓取光标,表示可拖动 */
cursor: grabbing; /* 抓取中光标 */
cursor: zoom-in; /* 放大光标 */
cursor: zoom-out; /* 缩小光标 */
cursor: not-allowed; /* 禁止光标 */
cursor: wait; /* 等待光标 */
cursor: progress; /* 进度光标 */
cursor: text; /* 文本选择光标 */
cursor: move; /* 移动光标 */
cursor: help; /* 帮助光标 */
cursor: crosshair; /* 十字光标 */
}
打印样式
/* 打印样式 */
@media print {
/* 隐藏不需要打印的元素 */
.no-print, .navigation, .footer, .ads {
display: none !important;
}
/* 确保背景色和图像可见 */
* {
-webkit-print-color-adjust: exact;
color-adjust: exact;
}
/* 避免分页符出现在不适当的位置 */
h1, h2, h3, h4, h5, h6 {
page-break-after: avoid;
break-after: avoid;
}
img, table {
page-break-inside: avoid;
break-inside: avoid;
}
/* 添加URL到链接后面 */
a[href]:after {
content: " ("attr(href) ")";
font-size: 90%;
}
/* 设置页面边距 */
@page {
margin: 2cm;
}
}
总结
- CSS变量:提供了重用值和创建动态主题的能力
- CSS函数:如calc()、min()、max()和clamp(),增强了样式的计算能力
- 滤镜和混合模式:提供了丰富的视觉效果
- 形状和裁剪:允许创建非矩形的界面元素
- 遮罩:提供了复杂的内容显示控制
- 容器查询:基于容器大小而非视口大小应用样式
- 滚动捕捉:创建流畅的滚动体验
- 逻辑属性:使CSS更适应不同的书写模式和阅读方向
- 支持查询:允许检测浏览器对特定CSS特性的支持
- 自定义光标:增强用户交互体验11. 打印样式:优化打印输出