问题
I'm using Spring MVC and the Thymeleaf view engine. I have an external style.css file with the CSS for my page. In the CSS file, I want to refer to a relative image URL.
This is my style.css file:
.background {
width: 100%;
background-image: url('/path/to/image/bg.png');
}
The above tries to access an image with the following URL, which doesn't exist:
http://localhost/path/to/image/bg.png
My real image is at:
http://localhost/myapp/path/to/image/bg.png
This StackOverflow question gives the answer to my question for inline CSS: How to set background url for css files in thymeleaf?
But how do I do this for an external .css file?
回答1:
Put all your images folder structure with images path/to/image/bg.png
inside the images
folder under resources/static
. Then refer to it in CSS as:
.background {
width: 100%;
background-image: url('../images/path/to/image/bg.png');
}
And then you can use this CSS in your templates as:
<head>
<link rel="stylesheet" media="screen" th:href="@{/css/application.css}"/>
</head>
Your files structure should look like this:
来源:https://stackoverflow.com/questions/40105511/thymeleaf-url-expression-in-css-file