前言:文字描边有两种实现方式
1. text-shadow
设置 8 个方向的文字阴影,缺点是只有八个方向,文字转角处可能有锯齿状。不支持文字透明,设置 color: transparent,文字会成描边颜色。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" /> <title>document</title> <style> body { background: #000; } p { text-align: center; font-weight: bold; font-size: 5em; color: red; text-shadow: 0 -2px #fff, 2px 0px #fff, 0 2px #fff, -2px 0 #fff, -2px -2px #fff, 2px 2px #fff, 2px -2px #fff, -2px 2px #fff; } </style> </head> <body> <p>人生若只如初见</p> <p>何事秋风悲画扇</p> <script></script> </body> </html>
2. -webkit-text-stroke
描边属性,支持文字透明。只留描边。缺点是兼容性,文字会变细,文字变细可以通过 JS 解决。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" /> <title>document</title> <style> body { background: #000; } p { font-weight: bold; font-size: 5em; color: red; -webkit-text-stroke: 4px #fff; position: relative; } p::after { content: attr(data-text); position: absolute; left: 0; top: 0; text-align: center; -webkit-text-stroke: 0; } </style> </head> <body> <p>人生若只如初见</p> <p>何事秋风悲画扇</p> <script> const ps = document.querySelectorAll("p"); ps.forEach((p) => { p.dataset.text = p.textContent; }); </script> </body> </html>