Spring项目中HTML无法引入CSS文件的问题求助
Hey there, I notice your login.css isn't taking effect in your Thymeleaf view—let's walk through the fixes here, since relative paths and Spring's static resource rules are usually the culprit here.
First: Make Sure Your CSS is in the Right Folder
Spring (especially Spring Boot) looks for static resources like CSS, JS, and images in specific default directories:
src/main/resources/staticsrc/main/resources/publicsrc/main/resources/resources
Double-check that your login.css is placed inside src/main/resources/static—this is the most common and recommended location. If it's somewhere else, move it here first.
Second: Update Your CSS Reference to Use Thymeleaf's URL Syntax
Your current code uses a relative path ./login.css, which doesn't play nicely with Thymeleaf's template resolution or Spring's resource handling. Instead, use Thymeleaf's URL expression @{...} to let Spring resolve the correct path automatically.
Replace this line:
<link rel="stylesheet" type="text/css" href="./login.css">
With this:
<link rel="stylesheet" type="text/css" th:href="@{/login.css}">
The @{/login.css} tells Thymeleaf to generate the full correct URL to your static CSS file, even if your app is deployed under a custom context path.
Bonus Troubleshooting Steps If It Still Doesn't Work
If the above steps don't fix it, try these checks:
- Verify the filename and path are 100% correct (case matters on Linux-based servers, so make sure
login.cssisn'tLogin.cssby accident) - Clear your browser cache—sometimes old cached resources prevent new CSS from loading. You can do a hard refresh with
Ctrl+Shift+R(Windows/Linux) orCmd+Shift+R(Mac) - If you've customized your Spring config, check
application.properties/application.ymlforspring.resources.static-locationsand ensure it includes the folder where your CSS lives
Here's how your updated <head> section should look:
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <title>Login</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Fixed CSS reference using Thymeleaf --> <link rel="stylesheet" type="text/css" th:href="@{/login.css}"> </head>
That should get your CSS working properly in no time!
内容的提问来源于stack exchange,提问作者Todor Dimitrov

