HTML5如何给文字加删除线_删除线样式实现与自定义方法【技巧】

最快实现删除线的方式是使用 text-decoration: line-through,它原生支持、无需额外标签或JS,但无法单独控制颜色和粗细;如需自定义,应使用 text-decoration-color 和 text-decoration-thickness(需三者同设),或用 ::after 伪元素模拟以获得完全控制。

text-decoration: line-through 最快实现删除线

直接给文字加删除线,最简单可靠的方式就是 CSS 的 text-decoration 属性。它原生支持 line-through 值,无需额外标签或 JS。

  • 适用于所有块级/行内元素,比如

  • 注意:它会继承,子元素也会带删除线,如需局部取消,得显式设 text-decoration: none
  • 不能单独控制删除线颜色或粗细——这是它的硬限制,不是写法错了
span.deleted {
  text-decoration: line-through;
}

想改删除线颜色或粗细?必须用 text-decoration-colortext-decoration-thickness

HTML5 + CSS Text Decoration Level 3 标准已支持这些属性,但兼容性有坑:Chrome 90+、Firefox 97+、Safari 15.4+ 才稳定支持 text-decoration-thicknesstext-decoration-color 支持稍好(Chrome 57+,Firefox 36+)。

  • text-decoration-thickness 可设 autofrom-font、具体像素值(如 2px)或百分比
  • 三者需同时设置才生效:text-decoration-line: line-through + text-decoration-color + text-decoration-thickness
  • 旧版浏览器会忽略后两个属性,回退到默认删除线(黑色、细线),属于安全降级
p.highlighted {
  text-decoration-line: line-through;
  text-decoration-color: #ff6b6b;
  text-decoration-thickness: 3px;
}

需要完全自定义位置/角度/动画?用伪元素 ::after 模拟删除线

当标准属性不够用——比如要让删除线斜穿文字、随文字变色、或加 hover 动画——就得放弃 text-decoration,改用 ::after 伪元素手动绘制一条线。

  • 核心思路:把文字设为 position: relative,再用 ::after 绝对定位画线
  • 可自由控制 widthheighttransform: rotate()background 等任意样式
  • 注意:伪元素默认不占文档流,且无法自动适配文字宽度,需用 width: 100% 或 JS 测量(后者复杂,一般用前者+微调)
span.custom-strike {
  position: relative;
  text-decoration: none;
}
span.custom-strike::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #ff416c, #ff4b2b);
  transform: translateY(-50%) rotate(-5deg);
}

慎用 标签:语义正确 ≠ 样式可控

是 HTML5 语义化标签,表示被删除的内容,浏览器默认渲染为删除线。但它只是语义载体,样式仍由 CSS 控制。

  • 不要指望它自带红字或特殊样式——所有现代浏览器都只默认加 text-decoration: line-through
  • 若项目需无障碍支持(如屏幕阅读器), 会读作“已删除”,比纯 CSS 更准确;但若只是视觉装饰,用 更轻量
  • 的区别:后者仅表示“不再准确/不推荐”,无时间维度含义,语义更弱

真正容易被忽略的是:删除线在高对比度模式(Windows 系统设置)下可能被强制覆盖为系统主题色,此时 text-decoration-color 无效,伪元素方案也需额外适配 @media (forced-colors: active)