CSS 文字装饰 text-decoration & text-emphasis

在 CSS 中,文字算是我们天天会打交道的一大类了,有了文字,则必不可少一些文字装饰。

本文将讲讲两个比较新的文字装饰的概念 text-decoration 与 text-emphasis,在最后,还会讲解使用 background 模拟文字下划线的一些有趣的动效。

text-decoration 文字装饰

text-decoration 意为文字装饰,在很早的规范 就已经存在了。譬如我们非常熟知的下划线 text-decoration: underline。

p { text-decoration: underline; }

image

而到了比较新的 ,text-decoration 得到了比较大的丰富更新,演化出了 text-decoration-line, text-decoration-color, text-decoration-style,和还未成为标准的 text-decoration-thickness 等属性,是它们的缩写。

其中:

text-decoration-line:控制用于设置元素中的文本的修饰类型,是在文本下方、上方还是贯穿文本

text-decoration-style:不仅仅是实线 solid,类似于 border-style,还支持双实线 double、点划线 dotted、虚线 dashed 以及非常有意思的 wavy 波浪线

text-decoration-color:这个好理解,控制颜色

text-decoration-thickness:控制修饰线的粗细

这里有张非常好的图,帮助大家快速理解:

image

CodePen Demo -- Text-decoration Demo

text-decoration-line 可以同时设置

有意思的一点是,text-decoration-line 可以同时设置。

p { text-decoration-line: overline underline line-through; }

image

我们可以得到上中下三条线。

text-decoration 可以进行过渡与动画

text-decoration 的每个值都是可以进行过渡与动画的。合理利用,在一些文本强调的地方,非常有用。

<p>Lorem ipsum dolor</p> .transition { text-decoration-line: underline; text-decoration-color: transparent; text-decoration-thickness: 0.1em; cursor: pointer; transition: .5s; &:hover { text-decoration-color: pink; text-decoration-thickness: 0.15em; color: pink; } }

CSS 文字装饰 text-decoration & text-emphasis

配合另外一个属性 text-underline-offset,我们还可以实现如下图这样有趣的效果:

CSS 文字装饰 text-decoration & text-emphasis

当然,上述的例子中使用了 text-underline-offset 的变换,但是本身 CSS 是不支持 text-underline-offset 的过渡动画的,这里借助了 CSS @property 巧妙的实现了 text-underline-offset 的过渡动画,感兴趣的可以具体了解下 CSS @property 的用法。

CodePen Demo -- 文字下划线过渡动画效果

text-decoration-color 与 color 分离

text-decoration-color 与 color 是可以不一样的,类似于这样。

.color { text-decoration-style: wavy; cursor: pointer; transition: .5s; &:hover { color: transparent; text-decoration-color: pink; } }

CSS 文字装饰 text-decoration & text-emphasis

有意思,经过这样,我们其实得到了一条波浪线。

如果我们把 wavy 下划线加给元素的伪元素,然后在 hover 的时候添加一个动画,让波浪线动起来,得到一个非常好的强调 hover 效果:

<p data-content="Lorem ibsum dolor Lorem ibsum dolor">Lorem ibsum dolor</p> .animation { position: relative; text-decoration: none; overflow: hidden; cursor: pointer; line-height: 2; &::before { content: attr(data-content); position: absolute; top: 0; left: 0; color: transparent; white-space: nowrap; text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: #000; z-index: -1; } &:hover::before { animation: move 3s infinite linear; } } @keyframes move { 100% { transform: translate(-209px, 0); } }

CSS 文字装饰 text-decoration & text-emphasis

我们利用伪元素添加了一段长于文本本身的文本,并且颜色为透明,但是设置了波浪线的颜色,然后 hover 的时候,通过运动伪元素的 translate 进行波浪线的位移,稍微调试一下 translate 的值,可以做到动画的首尾相连,实现运动的波浪线的效果。

CodePen Demo -- text-decoration Demo

text-emphasis 文字强调

text-emphasis 意为文字强调,是 才新增的一个属性,用于增强文字强调的效果。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwyjg.html