如何从子目录引入/关联CSS及HTML文件?
Got it, let's tackle this path problem you're facing. The root issue here is that relative paths work based on the current page's URL. So when you're in subdir/index.html, the path css/global.css tries to look for subdir/css/global.css which doesn't exist—your CSS is actually one level up in the root css/ folder. Same goes for your includes.
Here are three solid solutions to fix this, ordered by how maintainable they are:
1. Use Absolute Paths (Recommended)
This is the most reliable approach, especially if you plan to add more subdirectories later. Instead of relative paths, use paths that start with a / to reference files from the root of your server.
For both your root index.html and subdir/index.html, update your links and includes to look like this:
<!-- CSS links --> <link href="/css/global.css" rel="stylesheet" /> <link href="/css/site.css" rel="stylesheet" /> <!-- Includes (assuming you're using server-side includes like Apache SSI) --> <!--#include virtual="/includes/header.html" --> <!--#include virtual="/includes/nav.html" --> <!--#include virtual="/includes/footer.html" -->
This tells the server to always look for the files starting from the root directory, no matter where the current page is located.
2. Add a <base> Tag to Your HTML
If you want to keep using relative paths but set a base URL for all relative links, add a <base> tag in the <head> section of every HTML file.
Add this to both your root and subdirectory HTML files:
<head> <base href="/"> <!--###�es 英 Tobiaso �ve/journal学.p plotting maintain <link href="css/global.css" rel="stylesheet" /> <link href="css/site.css" rel="stylesheet" /> <!-- rest of your head content --> </head>
The <base> tag sets the root URL for all relative links on the page, so css/global.css will always resolve to /css/global.css regardless of the page's location.
3. Use Parent Directory References (../)
For the subdirectory files specifically, you can adjust the relative paths to go up one level before accessing the CSS and includes.
In subdir/index.html, update your paths to:
<!-- CSS links --> <link href="../css/global.css" rel="stylesheet" /> <link href="../css/site.css" rel="stylesheet" /> <!-- Includes --> <!--#include virtual="../includes/header.html" --> <!--#include virtual="../includes/nav.html" --> <!--#include virtual="../includes/footer.html" -->
The ../ tells the server to go up one directory level first, then look for the css/ and includes/ folders. This works but can get messy if you add deeper nested directories later.
Content of the question originates from stack exchange, question author jlconlin

