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

相关推荐
昔人'1 小时前
css 高度从 0 到 auto 的动画效果 `interpolate-size: allow-keywords`
前端·css
冲!!2 小时前
SCSS 中的Mixins 和 Includes,%是什么意思
前端·css·scss
梦6502 小时前
CSS新特性
css
BillKu16 小时前
vue3 样式 css、less、scss、sass 的说明
css·less·sass·scss
乖女子@@@18 小时前
css3新增-网格Grid布局
前端·css·css3
Sapphire~21 小时前
重学前端013 --- 响应式网页设计 CSS网格布局
前端·css
二十雨辰1 天前
歌词滚动效果
前端·css
dllmayday1 天前
FontForge 手工扩展 iconfont.ttf
css·qt
BUG创建者1 天前
html获取16个随机颜色并不重复
css·html·css3
面向星辰2 天前
html中css的四种定位方式
前端·css·html