1. 可行的幾種方式
- text-shadow
- –webkit-text-stroke
- svg
1.1. text-shadow 描邊
MDN text-shadow
代碼
<div class="text stroke">新年快樂</div>
用 text-shadow 實(shí)現(xiàn)八個(gè)方向的文字陰影。
.text {
font-size: 150px;
color: white;
font-weight: 400;
}
.stroke {
text-shadow: 4px 0 #000,
-4px 0 #000,
0 4px #000,
0 -4px #000,
4px 4px #000,
-4px -4px #000,
4px -4px #000,
-4px 4px #000;
}
優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
- 兼容性好
缺點(diǎn)文章來源:http://www.zghlxwxcb.cn/news/detail-780962.html
- 文字邊緣會(huì)有鋸齒。
如上圖,當(dāng)文字很大時(shí),尤其明顯。因?yàn)槲覀冎辉O(shè)置了8個(gè)方向的陰影,這些方向交界處容易出問題。
- 文字必須設(shè)置顏色
如果我們把文字設(shè)置為透明色,描邊就失效了,因?yàn)閠ext-shadow本質(zhì)就是設(shè)置文本陰影。
color: transparent;
效果:文字透明了,文字陰影徹底顯現(xiàn)了出來。
1.2. text-stroke 描邊
MDN text-stroke
實(shí)現(xiàn)
<div class="text stroke">新年快樂</div>
.text {
font-size: 150px;
color: white;
font-weight: 400;
}
.stroke {
-webkit-text-stroke: 4px #000;
}
可以實(shí)現(xiàn)絲滑的描邊效果!
注意:text-stroke 是居中描邊,我們這里設(shè)置了 4px 的描邊,實(shí)際上會(huì)在文字內(nèi)部和外部各畫2px。直接使用 text-stroke 來描邊會(huì)讓文字本身變瘦。
比如,我們繼續(xù)加大描邊的寬度,設(shè)置8px。
-webkit-text-stroke: 8px #000;
可以看到最終的效果是文字的白色部分越來越少。
如果你覺得這樣無所謂,那這樣實(shí)現(xiàn)也可以。但如果你不想要文字本身的寬度(白色部分)改變,那么可以用下面的技巧來實(shí)現(xiàn)。
我們?cè)黾右粋€(gè)偽元素來,完整代碼如下:
<div class="text stroke" data-content="2023, 新年快樂!">2023, 新年快樂!</div>
.text {
font-size: 150px;
color: white;
font-weight: 400;
position: relative;
z-index: 0;
}
.text::after {
content: attr(data-content);
-webkit-text-stroke: 8px #000;
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
這里我們給偽元素設(shè)置描邊,并且將原本的文字覆蓋在其上面,能完美實(shí)現(xiàn)描邊,且沒有改變?cè)镜奈淖謱挾取?br> 注意:我們?cè)鞠雽?shí)現(xiàn)4px的描邊,前面我們提到text-stroke是居中描邊,因此為了實(shí)現(xiàn)效果我們實(shí)際上要設(shè)置8px。
優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
- 效果好,描邊絲滑。
缺點(diǎn)
- 兼容性一般,需要加 -webkit 前綴
1.3. svg 描邊
實(shí)現(xiàn)
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="200">
<text
class="text stroke"
x="0"
y="0"
alignment-baseline="text-before-edge"
text-anchor="start"
>
2023, 新年快樂!
</text>
</svg>
.text {
font-size: 150px;
fill: white;
font-weight: 400;
}
.stroke {
stroke: #000;
stroke-width: 4px;
}
通過設(shè)置stroke + stroke-width 即可實(shí)現(xiàn)描邊。
注意:這里實(shí)現(xiàn)的效果也類似前面 text-stroke 的居中描邊,實(shí)際上文字本身也變瘦了。
為了不讓文字本身變瘦,我們可以用paint-order屬性來改變描邊繪制的方式。
.stroke {
stroke: #000;
stroke-width: 8px;
paint-order: stroke;
}
同樣實(shí)現(xiàn)了描邊效果,且不改變文字原本寬度。
優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
- 兼容性最好
- 通過 stroke-linejoin 屬性,還可以對(duì) svg 的描邊有更靈活的控制
.stroke1 {
stroke-linejoin: round;
}
.stroke2 {
stroke-linejoin: bevel;
}
.stroke3 {
stroke-linejoin: miter;
}
缺點(diǎn)
- 需要設(shè)置svg 的寬高,文字排版可能不夠靈活
總結(jié)
我們介紹了css中三種文字描邊的實(shí)現(xiàn)方式,它們各有優(yōu)缺點(diǎn),可以根據(jù)實(shí)際的應(yīng)用場(chǎng)景選擇最合適的方式!文章來源地址http://www.zghlxwxcb.cn/news/detail-780962.html
到了這里,關(guān)于【CSS】文字描邊的三種實(shí)現(xiàn)方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!