CSS 大约有两百个属性。很多属性都是相互关联的,理清楚每一个属性细节是不可能的。所以,本文分享一些有用的 CSS 小技巧,方便开发者和设计师参考。

1. 打字效果

测试.gif

网页设计变得越来越有创意。在 CSS 动画的协调下,你的网页会像活的一样。在这个例子中,我们将使用 animation 和 @keyframes 属性去实现打字效果。

具体来说,在这个演示中,我们通过 steps() 属性来实现分割文本的效果。首先,你必须指定 step() 中传入的数量,在这个例子中就是文本的长度。

接着,第二步,我们使用 @keyframes 去声明什么时候开始执行动画。

如果你在文本 Typing effect for text 后面添加内容,而不改变 step() 中的数字,将不会产生这种效果。

这种效果并不是特别新鲜。然而,很多开发者却使用 JavaScript 库去实现,而不是使用 CSS。

<div class="typing"> <div class="typing-effect">Typing effect for text</div></div> 
 .typing { height: 80vh; display: flex; align-items: center; justify-content: center; } .typing-effect { width: 22ch; white-space: nowrap; overflow: hidden; border-right: 3px solid; font-family: monospace; font-size: 2em; animation: typing 2s steps(22), effect .5s step-end infinite alternate; } @keyframes typing { from { width: 0; } } @keyframes effect { 50% { border-color: transparent; } } 

2. 透明图片阴影效果

image.png

你是否使用过 box-shadow 为透明的图片添加阴影,却让其看起来像添加了一个边框一样?然而解决方案是使用 drop-shadow。

drop-shadow 的工作方式是,其遵循给给定图片的 Alpha 通道。因此阴影是基于图片的内部形状,而不是显示在图片外面。

<div class="transparent-shadow"> <div class="margin-right"> <div class="margin-bottom align-center">box-shadow</div> <img class="box-shadow" src="https://stackdiary.com/wp-content/uploads/2022/02/logo.png" alt="box-shadow example (transparent)" /> </div> <div> <div class="margin-bottom align-center">drop-shadow</div> <img class="drop-shadow" src="https://stackdiary.com/wp-content/uploads/2022/02/logo.png" alt="drop-shadow example (transparent)" /> </div> </div> 
.transparent-shadow { height: 80vh; display: flex; align-items: center; justify-content: center; } .margin-right { margin-right: 2em; } .margin-bottom { margin-bottom: 1em; } .align-center { text-align: center; } .box-shadow { box-shadow: 2px 4px 8px #3723a1; } .drop-shadow { filter: drop-shadow(2px 4px 8px #3723a1); } 

10. 使用 ::before 添加按钮的图标

image.png

每当我需要链接到外部其他资源的时候,我都会使用自定义的按钮来实现。准确来说,是一个添加图标的按钮。简单的谷歌搜索,你会发现很多 button generators ,但是我对可以随时使用的通用解决方案更感兴趣。

所以,为了实现这个目标,我为特定按钮创建了一个 :before 伪元素。需要声明的是,代码片段中的 content:"\0000a0"; 是 &nbsp; 的 Unicode 转义。

你可以通过宽高属性来调整图标的尺寸,以更好适应按钮样式。

 <div class="card"> <div class="card-body"><a href="" target="_blank" class="btn btn-docu" rel="noopener">Documentation</a></div> </div> 
 .card .card-body .btn { display: block; width: 200px; height: 48px; line-height: 48px; background-color: blue; border-radius: 4px; text-align: center; color: #fff; font-weight: 700; } .card .card-body .btn-docu:before { content: '\0000a0'; display: inline-flex; height: 24px; width: 24px; line-height: 24px; margin: 0px 10px 0px 0px; position: relative; top: 0px; left: 0px; background: url(https://stackdiary.com/docu.svg) no-repeat left center transparent; background-size: 100% 100%; }