CSS 无法从带有 php 'include' 的相对路径工作


CSS not working from relative path with php 'includes'

文件夹结构

 /
 |--index.php
 +--includes
 |--header.html
 +--css
 |--style.css

我的主项目文件夹中有 2 个子文件夹。 一个是名为"include"的文件夹,另一个称为"css"。我有我的- 主文件夹中index.php文件- header.html在我的'main/includes'文件夹中- style.css在我的'main/css'文件夹中

我的索引.php包括标题.html如下所示:include_once('includes/header.html');(这有效!

我的头.html文件像这样链接css:<link href='../css/style.css' type='text/css' rel='stylesheet'/>(这行不通!

我不明白为什么没有加载 css 文件。
我尝试使用基本标签,尽管我不确定我是否正确使用它。 <base href="http://localhost/main" />(这不起作用)

你应该尝试使用

<link href='css/style.css' type='text/css' rel='stylesheet'/>

由于index.phpcss文件夹位于同一级别。

<link href='../css/style.css' type='text/css' rel='stylesheet'/>

您要求服务器在不存在的index.php的上层目录中照顾style.css

您也可以使用/因为,它指向网站的文档根目录。

<link href="/css/style.css" type="text/css" rel="stylesheet" />

我想你不明白include是如何工作的。本质上,引用文件中的代码将被复制到主文件中,然后进行处理。因此,如果要将其包含在 index.php 中,则需要相应地引用 CSS 文件。

以下方法应该有效:

<link href="/css/style.css" type="text/css" rel="stylesheet" />

您会发现在使用HTML时,使用绝对路径是最容易的,这样即使您将其复制到根目录以外的文件夹中的文件,上述类似内容仍然有效。

$siteurl ="http://localhost/project";

(将此变量存储在配置文件中,以便全局使用)

<link href='../css/style.css' type='text/css' rel='stylesheet'/>

将更改为

<link href='<?php echo $siteurl;?>/css/style.css' type='text/css' rel='stylesheet'/>

只是从<link href='../css/style.css' type='text/css' rel='stylesheet'/>更改为<link href='css/style.css' type='text/css' rel='stylesheet'/>

如果您尝试使用 PHP require 在 html 文件中添加 CSS:

<style><?php require("css/style.css");?></style>

注意<style>标签很重要,否则它将回显纯文本