Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting CSS style attributes with thymeleaf

Tags:

css

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.

like image 391
Mushtaq Jameel Avatar asked Mar 19 '15 09:03

Mushtaq Jameel


People also ask

How do you add a style to Thymeleaf?

Adding CSS. We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main.

Can we use JavaScript with Thymeleaf?

In this tutorial, we learned how to call JavaScript functions in a Thymeleaf template. We started by setting up our dependencies. Then, we constructed our controller and template. Finally, we explored ways to call any JavaScript function inside Thymeleaf.

What is Classappend?

Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications.

How do you apply inline style?

An inline style may be used to apply a unique style for a single element. To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.


4 Answers

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.

like image 59
Leandro Carracedo Avatar answered Oct 03 '22 23:10

Leandro Carracedo


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>
like image 24
Jaroslav Avatar answered Oct 04 '22 00:10

Jaroslav


You can also use literal substitutions:

<div th:style="|background:url(@{/<path-to-image>});|"></div>
like image 25
Rafael Takashima Avatar answered Oct 03 '22 23:10

Rafael Takashima


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

like image 21
Ula Avatar answered Oct 04 '22 00:10

Ula