以下是一些不常用但非常实用的 CSS 属性,按场景分类整理,附带实际应用示例:
1. 交互体验增强
caret-color
控制输入框光标的颜色,与品牌色保持一致:
input {
caret-color: #ff6b6b;
}
scroll-behavior
实现平滑滚动,无需 JavaScript:
html {
scroll-behavior: smooth;
}
pointer-events
禁用元素的鼠标事件,常用于"穿透"遮罩层或禁用按钮:
.disabled-overlay {
pointer-events: none; /* 点击会穿透到下层元素 */
}
touch-action
控制触摸屏上的默认手势(如缩放、滚动),优化移动端体验:
.swipe-card {
touch-action: pan-y; /* 只允许垂直滚动,禁止水平默认行为 */
}
overscroll-behavior
阻止滚动链(iOS 橡皮筋效果或 Android 发光效果),常用于模态框:
.modal-content {
overscroll-behavior: contain; /* 滚动到底不会带动父元素 */
}
2. 布局与盒模型
aspect-ratio
强制元素保持固定宽高比,替代旧的 padding 技巧:
.video-container {
aspect-ratio: 16 / 9;
width: 100%;
}
isolation
创建新的层叠上下文,解决 z-index 混乱问题:
.component {
isolation: isolate; /* 内部 z-index 不会与外部干扰 */
}
contain
性能优化利器,告诉浏览器该元素独立于文档流,减少重绘范围:
.widget {
contain: layout paint; /* 内部变化不影响外部布局 */
}
gap (用于 Flexbox)
很多人知道 Grid 的 gap,但 Flexbox 也支持:
.flex-list {
display: flex;
gap: 20px; /* 无需 margin hack */
}
3. 文本排版
font-variant-numeric
控制数字显示样式,特别适合财务报表:
.price {
font-variant-numeric: tabular-nums; /* 等宽数字,列对齐 */
/* 或者 oldstyle-nums 用于正文的旧式数字 */
}
hyphens
自动断字(需要设置 lang 属性):
p {
hyphens: auto;
word-wrap: break-word;
}
tab-size
控制代码块中 Tab 字符的宽度:
pre {
tab-size: 2; /* 2 个空格宽度 */
}
text-rendering
优化文本渲染,牺牲性能换取清晰度:
.logo {
text-rendering: optimizeLegibility; /* 更好的字距和连字 */
}
writing-mode
垂直排版,用于传统中文或日文:
.vertical-text {
writing-mode: vertical-rl;
text-orientation: upright; /* 文字直立而非旋转 */
}
4. 视觉效果
mix-blend-mode
创建 Photoshop 级别的混合模式效果:
.overlay-text {
mix-blend-mode: difference; /* 自适应背景对比色 */
color: white;
}
clip-path
复杂裁剪,替代简单的 border-radius:
.avatar {
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); /* 六边形 */
/* 或 circle(50% at 50% 50%) 圆形 */
}
shape-outside
让文本环绕不规则形状(需配合 float):
.float-image {
float: left;
shape-outside: circle(50%); /* 文字沿圆形环绕 */
clip-path: circle(50%);
}
image-rendering
控制缩放算法,像素艺术必备:
.pixel-art {
image-rendering: pixelated; /* 放大时保持锐利边缘 */
width: 400px;
}
backdrop-filter
毛玻璃效果(iOS 风格):
.glass {
background: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
}
5. 实用工具属性
all
一键重置元素所有样式:
.button-reset {
all: unset; /* 或 initial, inherit */
cursor: pointer;
}
resize
允许用户调整元素大小(textarea 默认有,可应用于其他元素):
.resizable-panel {
resize: horizontal;
overflow: auto;
}
user-select
控制文本是否可选择:
.no-copy {
user-select: none; /* 禁止选择 */
}
.code-snippet {
user-select: all; /* 单击全选 */
}
appearance
移除浏览器默认样式(常用于自定义表单控件):
.custom-checkbox {
appearance: none; /* 清除默认样式 */
width: 20px;
height: 20px;
border: 2px solid #333;
}
6. 滚动吸附(Scroll Snap)
创建轮播图或分页效果,无需 JS:
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
}
.carousel > div {
flex: 0 0 100%;
scroll-snap-align: center;
}
建议尝试的组合技:
- 毛玻璃 + 混合模式:创建现代玻璃拟态 UI
aspect-ratio+object-fit: cover:完美响应式图片容器scroll-behavior: smooth+scroll-snap-type:原生平滑轮播contain: paint:在复杂单页应用(SPA)中显著提升滚动性能
这些属性在现代浏览器中支持良好(IE 除外),可以安全地在生产环境中使用。