You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thymeleaf中内联注入CSS属性?

解决Spring + Thymeleaf邮件内联CSS注入颜色变量的问题

Thymeleaf原生支持th:style属性,同时还有th:styleappend属性可以更优雅地实现你的需求,以下是两种可行方案:

方案一:用th:style整合所有样式

把固定样式和动态变量拼接在一起,通过th:style一次性设置完整的内联样式:

<span 
  th:text="${newStateText}" 
  th:style="'display: inline-block; padding: 0.35em 0.65em; font-size: .75em; font-weight: 700; line-height: 1; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: 1rem; background-color: ' + ${newStateBackgroundColor} + '; color: ' + ${newStateColor} + ''"
>
</span>

方案二:用th:styleappend追加动态样式

如果想保留原有的style属性里的固定样式,只追加动态的颜色属性,推荐用th:styleappend,它会在原有样式基础上添加新的规则:

<span 
  th:text="${newStateText}" 
  style="display: inline-block; padding: 0.35em 0.65em; font-size: .75em; font-weight: 700; line-height: 1; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: 1rem;"
  th:styleappend="'background-color: ' + ${newStateBackgroundColor} + '; color: ' + ${newStateColor} + ''"
>
</span>

说明

  • th:style会完全替换元素原有的style属性,适合需要整体动态控制样式的场景。
  • th:styleappend仅追加新的样式规则,不会覆盖原有样式,更适合你这种保留固定样式、仅注入动态属性的需求。

内容的提问来源于stack exchange,提问作者Ramiro Moya Isnaldi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:30:53