27

I have a problem with CSS and Thymeleaf.

In my Spring boot app, I have this structure:

  • src/main/resource/static/css (for css files)
  • src/main/resource/static/templates (for html file)

Now, with my html page named ErrorPage and css file named Layout.css, using Thymeleaf I have, in the head of ErrorPage:

<link href="../css/Layout.css" th:href="@{css/Layout.css}" type="text/css" />

But this does not work.

What am I doing wrong?

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
Luca Sepe
  • 733
  • 4
  • 19
  • 30
  • Can you verify this, is your **ErrorPage** within **src/main/resources/static/templates** or **src/main/resources/templates**? If it's within the first one, it means it's handled as a **static resourc**e, which means Thymeleaf won't be used to render your page. If it's in the second one, then it can use Thymeleaf, but it probably also means you're using it as a view within a controller. You have to work relatively upon the location of the controller, rather than the folder structure. Share your controller/configuration that uses this errorpage HTML. – g00glen00b Jan 11 '17 at 10:11
  • What does not work? The ErrorPage does not render or it renders but the css file can't be downloaded? Do you use spring security? – Lachezar Balev Jan 11 '17 at 11:07

3 Answers3

47

Move your template folder right under resources:

  • src/main/resource/static/css (for CSS files);
  • src/main/resource/templates (for HTML templates).

Then correct the link tag as follows:

<link href="../static/css/Layout.css" th:href="@{/css/Layout.css}" rel="stylesheet" />
DimaSan
  • 12,264
  • 11
  • 65
  • 75
  • 7
    Why do we need both 'href' and 'th:href' simultaneously? – sva605 May 31 '17 at 12:07
  • We can easily remove HTML and use only Thymeleaf's attributes. Please read the answers here https://stackoverflow.com/questions/39757974/should-we-remove-html-attributes-while-using-thymeleaf – DimaSan Jun 01 '17 at 11:29
  • 10
    Not working for me giving error "cannot be context relative (/) or page relative unless you implement the org.thymeleaf.context.IWebContext" – alok Jan 22 '19 at 13:44
4

Move your template folder right under resources:

src/main/resources/static/css (for CSS files);
src/main/resources/templates (for HTML templates).

Then correct the link tag as follows (relative or absolute):

<link href="../css/firstcss.css" rel="stylesheet">
<link href="/css/secondcss.css" rel="stylesheet">

The old solution with static in front doesn't work for me.

Adrian
  • 505
  • 1
  • 6
  • 19
3

The main culprit of this behaviour is a custom security configuration which is very likely you are doing in your WebSecurityConfigurerAdapter subclass. If you use SpringBoot 2+ version you should add the following line in your WebSecurityConfigurerAdapter configuration

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

Semyon Evgrafov
  • 106
  • 1
  • 6