【问题标题】:How to deal with paths in CSS when including the same css file from multiple directories包含来自多个目录的相同css文件时如何处理CSS中的路径
【发布时间】:2016-06-27 17:00:27
【问题描述】:

我有以下文件夹结构

website 
    \styles\ 
         main.css
    \directory\
         page.php  
    \layout\ 
         background.jpg 
         common_includes.php 
    index.php 

main.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" />
 ... 

index.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 中的 background.jpg 的问题。

如何在不复制所有内容的情况下实现这一目标?

【问题讨论】:

    标签: php html css path


    【解决方案1】:

    使用绝对路径(相对于根目录)

    <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'); 
     }
    

    任何以“/”开头的路径都是相对于根目录的,无论你在哪里使用它都保持不变。 更多详情请阅读Having links relative to root?

    【讨论】:

    • 在 chrome 中打开页面,然后打开控制台检查哪个链接不起作用。它可能有 404 错误。检查它并显示结果,以便我可以为您提供相应的帮助。
    猜你喜欢
    • 2016-11-14
    • 2015-06-11
    • 2019-04-21
    • 1970-01-01
    • 2015-08-25
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多