我的自定义 CSS Hacks
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
经过多年的 UI 和网页设计经验,我收集了一份虽小但很实用的 CSS 小技巧清单,我几乎在每个项目、应用程序或网站中都会用到它们。
我希望你能从中学习,并将其运用到你的项目中。
请在下方评论区分享你最喜欢的 CSS 小技巧!
- 自定义网格
.grid {
position: relative;
margin: auto;
width: 1200px;
}
@media(max-width: 1200px) {
.grid {
width: 95%;
}
}
这样,您就可以设置自定义网格以在内部工作,并且可以针对不同的设备屏幕宽度编辑此网格。
- 设计一个自定义关闭图标
.close {
position: absolute;
padding: 5px;
font-style: normal;
font-weight: 600;
transform: scale(1.4);
cursor: pointer;
width: 20px;
height: 20px;
transition: all 0.3s;
z-index: 900;
}
.close::before {
position: absolute;
top: 4px;
left: 12px;
transform: rotate(-43deg);
content: '|';
}
.close::after {
position: absolute;
top: 4px;
left: 14px;
content: '|';
transform: rotate(43deg);
}
我设计了一个自定义图标元素,在 HTML 中任何需要使用它的地方,我只需添加这行代码:
<i class="close"></i>
- CSS变量
有些 CSS 代码很长,难以记忆,所以我直接把它们存储在一个 CSS 变量里,就这么简单。
:root {
--gradient: linear-gradient(324deg, rgba(119,0,255,1) 0%, rgba(41,4,255,1) 100%);
}
然后我就可以在 CSS 中这样调用它:
.box { background: var(--gradient) }
- 将所有内容都设置为边框框
* {
box-sizing: border-box
}
这样一来,我的所有元素尺寸都会统一,我也不用担心内边距、边框之类的东西会影响宽度和高度。
- 获取快速间隔元素 有时我需要在元素之间添加快速间隔元素
.spacer { height: 60px }
我在我的HTML代码中调用它:
<div class="spacer"></div>
- 自定义滚动条
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: #eee;
border-radius: 50px;
}
::-webkit-scrollbar-thumb {
background: green;
border-radius: 50px;
}
那个功能可以自定义滚动条,挺酷的。
- 自定义高光
::selection {
background: red;
color: white;
}
- 移除对 !important 的依赖 为了移除对 !important 的依赖,避免样式冲突,我只需让每个选择器都非常具体,例如:
.app .container .box h1 { color: green; }
而不是像这样设置样式
.app h1 {color:green;}
如果我需要更抽象的风格定义,
我会使用:
.app h1 { color:green }
.app .container .box h1.title {color:red}
希望你们喜欢!
你可以在下方评论区补充你的想法,我很想听听你的看法!
文章来源:https://dev.to/urielbitton/my-custom-css-hacks-4j85