PHP项目include引入head.php后CSS失效,求助排查问题
index.css Isn't Loading (and How to Fix It) Hey there! Let's break down why your CSS isn't working and fix it quickly.
The Root Problem
When you use include(__DIR__.'/includes/head.php') in index.php, the browser parses the CSS path relative to index.php (your root file), not relative to head.php (the included file).
Your original path in head.php:
<link rel="stylesheet" type="text/css" href="../css/index.css">
The ../ tells the browser to go up one level from index.php's location—but index.php is already in the root directory! There's no "up" level, so the browser can't find the CSS file.
Two Easy Fixes
Pick whichever works best for you:
1. Use a Root-Relative Path (Simplest)
Replace the CSS href with a path starting with /—this tells the browser to start looking from your website's root directory, no matter where the current file is:
<link rel="stylesheet" type="text/css" href="/css/index.css">
This works because your css folder is directly in the root, so /css/index.css points straight to it.
2. Use PHP's __DIR__ for an Absolute Path (More Robust)
If you want to make sure the path always works even if you move files around, use __DIR__ (which refers to the directory of the current file, head.php) to build the correct path:
<link rel="stylesheet" type="text/css" href="<?php echo __DIR__ . '/../css/index.css'; ?>">
Here, __DIR__ is the includes folder, so ../ takes us back to the root, then we point to css/index.css. PHP will output the correct full path relative to your server.
Quick Check
Double-check your project structure matches what you shared:
- index.php - css/ -- index.css - includes/ -- head.php
Either fix above should get your CSS loading properly!
内容的提问来源于stack exchange,提问作者user45678

