Mushtaq Jameel
Mushtaq Jameel

Reputation: 7083

Setting CSS style attributes with thymeleaf

How to set the background property of a style tag with a thymeleaf resolved url.

I have

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

Is there a <img th:src="${@/<path-to-image>}"> equivalent for setting style attributes in thymeleaf.

Upvotes: 21

Views: 69463

Answers (4)

Rafael Takashima
Rafael Takashima

Reputation: 121

You can also use literal substitutions:

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

Upvotes: 6

Jaroslav
Jaroslav

Reputation: 917

The answer suggested by @Leandro Carracedo did not work for me (but it helped along the way), I had to add second pair of brackets and '$' to get the value out of the variable

<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>

Upvotes: 9

Ula
Ula

Reputation: 2748

I hope it will help someone.

Please make sure that your image SIZE is SMALLER than screen size in pixels. Otherwise, neither 'background' nor 'background-image' did not work for me.

Leandro's syntax works fine. Consider using this one as well ( 'background-image' instead of 'background' )

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

This one stretches out the image instead of repeating it if image is smaller ( no need to state 'no-repeat' )

Upvotes: 3

Leandro Carracedo
Leandro Carracedo

Reputation: 7345

You could achieve that if you use th:style to set your style attribute:

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

Check this thread on thymeleaf forum.

Upvotes: 51

Related Questions