>我有以下文件夹结构
website
'styles'
main.css
'directory'
page.php
'layout'
background.jpg
common_includes.php
index.php
主.css包含背景图像,例如
#container {
background-image: url('../layout/background.jpg');
}
common_includes.php包含所有页面通用的CSS和JS文件。例如:
<link rel="stylesheet" type="text/css" href="styles/main.css" />
<link rel="stylesheet" type="text/css" href="styles/other.css" />
...
索引.php
<?php include_once '/layout/common_includes.php'; ?>
一切都完美,直到这里。
现在我想有一个包含其他页面的文件夹(/directory/page.php
)。
我希望page.php
使用相同的common_includes.php
.
显然,通过做:
<?php include_once '../layout/common_includes.php'; ?>
由于工作目录不同而不起作用。
我尝试复制common_includes.php以获得正确的路径:
common_includes_directory.php
<link rel="stylesheet" type="text/css" href="../styles/main.css" />
<link rel="stylesheet" type="text/css" href="../styles/other.css" />
...
我遇到了找不到CSS中背景.jpg的问题。
如何在不必复制所有内容的情况下实现这一点?
使用绝对路径(相对于根)
<link rel="stylesheet" type="text/css" href="/styles/main.css" />
<link rel="stylesheet" type="text/css" href="/styles/other.css" />
在 css 中使用
#container {
background-image: url('/layout/background.jpg');
}
任何以"/"开头的路径都是相对于root的,无论你在哪里使用它,它都保持不变。有关更多详细信息,请阅读具有相对于根的链接?