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

相关推荐
滔滔不绝tao2 小时前
自动化测试常用函数
前端·css·html5
autumn86811 小时前
什么是css?
css
Estrella1611 小时前
经典 web 页面排版:三栏布局
前端·css·面试
世俗ˊ12 小时前
CSS入门笔记
前端·css·笔记
茶茶只知道学习13 小时前
通过鼠标移动来调整两个盒子的宽度(响应式)
前端·javascript·css
susu108301891114 小时前
前端css样式覆盖
前端·css
东方翱翔14 小时前
CSS的三种基本选择器
前端·css
Fan_web15 小时前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
Java开发追求者15 小时前
在CSS中换行word-break: break-word和 word-break: break-all区别
前端·css·word
pink大呲花16 小时前
css鼠标常用样式
前端·css·计算机外设