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就非常容易了

相关推荐
牧杉-惊蛰3 小时前
disable-devtool 网络安全 禁止打开控制台
前端·css·vue.js
CoderYanger4 小时前
前端基础-HTML入门保姆级课堂笔记
前端·javascript·css·html
蓝胖子的多啦A梦6 小时前
低版本Chrome导致弹框无法滚动的解决方案
前端·css·html·chrome浏览器·版本不同造成问题·弹框页面无法滚动
ะัี潪ิื8 小时前
精灵图(雪碧图)的生成和使用
java·css
iuuia8 小时前
02--CSS基础
前端·css
苦夏木禾8 小时前
css实现表格中最后一列固定
前端·javascript·css
Dcc13 小时前
纯 css 实现前端主题切换+自定义方案
前端·css
华仔啊17 小时前
如何用 Vue3 打造高级音乐播放器?进度条+可视化效果,代码简洁可复用!
前端·css·vue.js
深蓝电商API1 天前
网页结构解析入门:HTML、CSS、JS 与爬虫的关系
javascript·css·html
Python私教2 天前
React 19 如何优雅整合 Ant Design v5 与 Tailwind CSS v4
前端·css·react.js