使用 thymeleaf 设置 CSS 样式属性

Setting CSS style attributes with thymeleaf

如何设置样式标签的背景 属性 解决了 thymeleaf url。

我有

<div style="background:url('<url-to-image>')"></div>

在 thymeleaf 中设置样式属性是否有 <img th:src="${@/<path-to-image>}"> 等价物。

如果您使用 th:style 设置您的样式属性,您可以实现:

<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

查看 thymeleaf 论坛上的 this 个帖子。

希望对大家有所帮助。

请确保您的图片尺寸小于屏幕尺寸(以像素为单位)。否则,'background' 和 'background-image' 都不适合我。

Leandro 的语法工作正常。也考虑使用这个( 'background-image' 而不是 'background' )

<div th:style="'background-image:url(' + @{/images/R1.jpg} + ');'">

如果图片较小(无需说明 'no-repeat' )

,则此图片会拉伸图片而不是重复图片

@Leandro Carracedo 建议的答案对我不起作用(但它一路帮助),我不得不添加第二对括号和“$”以从变量中获取值

<td th:style="'font-size:'+@{${headerTemplateTextSize}}+'; -webkit-margin-before: 0.67em; -webkit-margin-after: 0.67em; -webkit-margin-start: 0px;-webkit-margin-end: 0px; font-weight: 300; max-width: 100px'">
    <div>...</div>
</td>

您也可以使用文字替换:

<div th:style="|background:url(@{/<path-to-image>});|"></div>