css之文字描边


传统方式实现

html

<p>文字描边效果</p>

scss

@mixin text-stroke($color: #ffffff, $width: 1px) {
    
    
    text-shadow: 0 -#{
    
    $width} #{
    
    $color},
    #{
    
    $width} -#{
    
    $width} #{
    
    $color},
    #{
    
    $width} 0 #{
    
    $color},
    #{
    
    $width} #{
    
    $width} #{
    
    $color},
    0 #{
    
    $width} #{
    
    $color},
    -#{
    
    $width} #{
    
    $width} #{
    
    $color},
    -#{
    
    $width} 0 #{
    
    $color},
    -#{
    
    $width} -#{
    
    $width} #{
    
    $color};
}

p {
    
    
    font-size: 10rem;
    font-weight: bold;
    @include text-stroke(#ff0000, 2px);
}

通过scss编译后的css

p {
    
    
    font-size: 10rem;
    font-weight: bold;
    text-shadow: 0 -2px #ff0000, 2px -2px #ff0000, 2px 0 #ff0000, 2px 2px #ff0000, 0 2px #ff0000, -2px 2px #ff0000, -2px 0 #ff0000, -2px -2px #ff0000;
}

优缺点

1、兼容性好。
2、描边不是很均匀。
3、文字如果设置为透明,那么就会显示描边的颜色,也就是不能设置文字颜色为透明。


第二种方式

html需要写两遍文字

<p data-cont="文字描边效果">文字描边效果</p>

html

<!-- 只需要在标签中写文字即可 -->
<p>文字描边效果</p>

<script>
	const p = document.querySelector('p');
	p.dataset.content = p.textContent;
</script>

scss

p {
    
    
    font-size: 10rem;
    font-weight: bold;
    -webkit-text-stroke: #ffffff 2px;
    // color: transparent;
    position: relative;
}

// 描边文字变小的解决方法之一
// 此方案不能设置文字为透明,设置了也无意义
// 如果想要字体透明,可以设置字体放大
p::after {
    
    
	// 动态读取属性
    content: attr(data-content);
    -webkit-text-stroke: 0;
    position: absolute;
    left: 0;
}

优缺点

扫描二维码关注公众号,回复: 15956897 查看本文章

1、兼容性还算可以。
2、描边后的文字会变细。
3、文字如果设置为透明,那么描边依然存在,透明的只是文字本身,不会影响到描边效果。
4、原理是被描边的文字,描边方式是居中描边。

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/131998742