How to set background url for css files in thymele

2019-04-09 02:32发布

I have a thymeleaf template where I don't have CSS files imported and wanted to declare style attribute for the body element with background-image: url{/image.jpg} property with relative image URL. I wanted to load the URL without including the application context name(/myapp/) it. It is similar to the problem over here, except it din't work for me.

CSS:

<style>
body {
    background: url(../img/Background.jpg)
                no-repeat center center fixed;
    background-size: cover;
}
</style>

But the above CSS doesn't work and it accessed the image at

http://localhost/img/Background.jpg. 

So, I had to give the value as url(/myapp/img/Background.jpg) for the image to load properly.

I have the mvc:resources configuration properly set in spring-context.xml for /img/ request to load properly and it works in other places.

spring-context.xml

<mvc:resources mapping="img/**" location="/WEB-INF/img/" />

So how to load the background url image css value dynamically using thymeleaf's relative url?

2条回答
该账号已被封号
2楼-- · 2019-04-09 02:41

In my case that helped: change brackets from curly to round

<style th:inline="text">
body{
    background: url([[@{/img/Background.jpg}]])
                no-repeat center center fixed;
}
</style>
查看更多
家丑人穷心不美
3楼-- · 2019-04-09 03:04

So, here's how to set dynamic relative paths in background image url property in the css using thymeleaf's inline text value,

<style th:inline="text">
    body{
        background: url{[[@{/img/Background.jpg}]]}
                    no-repeat center center fixed;
    }
</style>

which loads the image using relative path and we don't have to specific the 'myapp' context name in the url.

查看更多
登录 后发表回答