SVG中的paint-order属性实现文字描边

过去只支持 SVG 元素

paint-order,表示绘制的顺序。

对于一个图形的绘制,顺序还是非常重要的。例如用SVG来绘制一个带边框的矩形

html 复制代码
<style>
  rect{
    fill: #FFE8A3;
    stroke: #9747FF;
    stroke-width: 4;
  }
</style>

<svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">
  <rect x="50" y="50" width="200" height="200" />
</svg>

效果如下:

默认情况下,描边是在填充上面的。如果要改变绘制顺序,也相当于改变层级,让填充覆盖在描边上面,可以使用paint-order属性

css 复制代码
rect{
  fill: #FFE8A3;
  stroke: #9747FF;
  stroke-width: 4;
  paint-order: stroke; /*先描边*/
}

表示先绘制stroke,效果如下:

看着变细了,这是因为描边是居中的,由于先绘制的描边,后绘制的填充颜色(后绘制的在上面),所以描边被填充盖住了一半。

这个属性在SVG文本中更明显,例如

html 复制代码
<style>
  text{
    font-size: 60px;
    fill: #FFE8A3;
    stroke: #9747FF;
    stroke-width: 4;
    font-weight: bold;
  }
</style>
<svg viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg">
  <text x="50%" y="50%" text-anchor="middle" dominant-baseline="middle">前端</text>
</svg>

文字本身都快被描边给覆盖了,下面调整一下

css 复制代码
text{
  font-size: 60px;
  fill: #FFE8A3;
  stroke: #9747FF;
  stroke-width: 4;
  font-weight: bold; 
  paint-order: stroke; /*先描边*/
}

这样就好多了

现在支持普通文本了

在普通HTML中,可以用-webkit-text-stroke来实现文字的描边效果,例如

html 复制代码
<h1 class="txt">前端侦探</h1>
<style>
  .txt{
  -webkit-text-stroke: 4px #9747FF;
}
</style>

以往通常使用绝对定位叠加的方式,手动让描边的那一层位于底部(可以用伪元素代替),就像这样

html 复制代码
<p class="text" data-title="前端侦探">前端侦探</p>
<style>
  .text{
    margin: 0;
    font-weight: bold;
    -webkit-text-stroke: 6px rgb(51, 51, 51);
	}
	.text::before{
	    content: attr(data-title);
	    position: absolute;
	    background-image: linear-gradient(#FFCF02, #FF7352);
	    background-clip: text;
	    -webkit-background-clip: text;
	    -webkit-text-fill-color: transparent;
	    -webkit-text-stroke: 0;
	}
</style>

不过现在,也可以像SVG一样,直接通过paint-order来改变层级了

html 复制代码
<h1 class="txt">前端侦探</h1>
<style>
  .txt{
  -webkit-text-stroke: 4px #9747FF;
  paint-order: stroke; /*先描边*/
}
</style>

相比SVG最大的好处就是,排版更加灵活,比如文本自动换行,SVG就无法直接实现,CSS就非常容易了

相关推荐
三十_A3 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
jumu2024 小时前
3 次 B 样条优化:为你的 Matlab 程序加速
css
亮子AI8 小时前
【css】列表的标号怎么实现居中对齐?
前端·css
冰暮流星11 小时前
css3如何引入外部字体
前端·css·css3
lcc18711 小时前
CSS 选择器
css
李少兄12 小时前
前端开发中的 transform、translate 与 transition
前端·css
李少兄13 小时前
深入理解前端中的透视(Perspective)
前端·css
A242073493013 小时前
使用jQuery动态操作HTML和CSS
css·html·jquery
三十_1 天前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css
行走的陀螺仪1 天前
重绘和重排怎么触发?怎么优化?
前端·css·性能优化·css3·浏览器原理