【问题标题】:Thymeleaf URL expression in .css file.css 文件中的 Thymeleaf URL 表达式
【发布时间】:2017-02-27 13:35:14
【问题描述】:

我正在使用 Spring MVC 和 Thymeleaf 视图引擎。我有一个外部 style.css 文件,其中包含我页面的 CSS。在 CSS 文件中,我想引用相对图像 URL。

这是我的 style.css 文件:

.background {
    width: 100%;
    background-image: url('/path/to/image/bg.png');
}

上面尝试使用以下不存在的 URL 访问图像:

http://localhost/path/to/image/bg.png

我的真实形象在:

http://localhost/myapp/path/to/image/bg.png

这个 StackOverflow 问题回答了我的内联 CSS 问题:How to set background url for css files in thymeleaf?

但是如何为外部 .css 文件执行此操作?

【问题讨论】:

    标签: css background-image thymeleaf relative-path


    【解决方案1】:

    将所有带有图像path/to/image/bg.png 的图像文件夹结构放在images 文件夹中resources/static 下。然后在 CSS 中将其称为:

    .background {
        width: 100%;
        background-image: url('../images/path/to/image/bg.png');
    }
    

    然后你可以在你的模板中使用这个 CSS:

    <head>
        <link rel="stylesheet" media="screen" th:href="@{/css/application.css}"/>
    </head>
    

    您的文件结构应如下所示:

    【讨论】:

    • 背景图片:url('../images/path/to/image/bg.png');
    • @MarufHamidi 完全正确!感谢您的更正。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2021-11-15
    • 2019-04-19
    • 1970-01-01
    • 2014-12-05
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多