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

相关推荐
社恐的下水道蟑螂17 分钟前
从字符串到像素:深度解析 HTML/CSS/JS 的页面渲染全过程
javascript·css·html
行走的陀螺仪1 小时前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3
午安~婉3 小时前
HTML CSS八股
前端·css·html
有事没事实验室3 小时前
css变量
前端·css
杂鱼豆腐人6 小时前
【自用】CSS查漏补缺
前端·css
码银6 小时前
【简易聊天室】使用 HTML、CSS、JavaScript 结合 WebSocket 技术实现
javascript·css·node.js·html
Justineo9 小时前
TemPad Dev:设计与实现
前端·javascript·css
我穿棉裤了10 小时前
使用css 给div添加四角线框
前端·css
musenh20 小时前
css样式学习
css·学习·css3
木易 士心21 小时前
CSS 中 `data-status` 的使用详解
前端·css