以下是 20 个高效实用的 CSS 单行代码合集,助你快速解决常见的前端开发问题:
.parent { display: flex; justify-content: center; align-items: center; }
一行实现子元素的水平和垂直居中。
.text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
单行文本溢出时自动显示省略号。
.clearfix { overflow: auto; }
替代传统的 clear: both
,更简洁的浮动清除方案。
.container { line-height: 300px; }
通过 line-height
等于容器高度实现单行文本垂直居中。
body { background: var(--bg, #fff); color: var(--text, #333); }
结合 CSS 变量和媒体查询 @media (prefers-color-scheme: dark)
快速适配主题。
.hero { background: url(bg.jpg) center/cover no-repeat; }
一行代码设置全屏自适应背景图。
::-webkit-scrollbar { width: 8px; background: #f1f1f1; }
仅用 WebKit 内核浏览器支持的样式美化滚动条。
button { -webkit-tap-highlight-color: transparent; }
消除移动端点击按钮时的默认灰色背景。
.unselectable { user-select: none; }
防止用户选中指定元素内的文本。
.blur { backdrop-filter: blur(10px); }
为元素添加背景模糊效果(部分浏览器支持)。
.grid { grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); }
自适应等宽网格布局,自动换行且内容等宽。
p::first-letter { text-transform: uppercase; }
快速实现段落首字母大写效果。
.button { background: linear-gradient(90deg, #ff6b6b, #4ecdc4); }
直接定义渐变背景色,无需额外图片。
.img { object-fit: cover; }
让图片填充容器并保持比例,避免拉伸变形。
.card { box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
快速添加柔和阴影提升层次感。
.text { -webkit-font-smoothing: antialiased; }
让字体在非 Retina 屏幕上显示更清晰(macOS 生效)。
.long-text { word-break: break-all; }
长文本强制换行,避免破坏布局。
:root { --primary-color: #2ecc71; }
定义全局 CSS 变量,便于主题统一管理。
.link { transition: all 0.3s ease-in-out; }
为元素变化添加平滑过渡效果。
.hide-scrollbar { scrollbar-width: none; }
隐藏滚动条但仍可滚动(Firefox 生效,Chrome 需配合 ::-webkit-scrollbar
)。
以上代码均经过实战检验,建议根据项目需求调整参数。掌握这些技巧可大幅提升开发效率!