You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP项目include引入head.php后CSS失效,求助排查问题

Why Your 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:40:34