PHP网站 - 在子目录中加载样式表

问题描述:

I'm building a PHP based site with this directory structure

index.php

css

  • style.css
  • bootstrap.css

includes

  • header.php
  • footer.php

bikes

  • road.php
  • mountain.php

The Problem

So I'm working on road.php and I obviously need to be able to link to both style.css and bootstrap.css, but when I declare at the start of road.php to include the header.php and footer.php it is like as if it cannot find the stylesheets and the site reverts back to the default 1990s look.

I have also found that any form of link on the page loads a 404. I'm only just starting out with PHP because I need some more power in my sites, but I just can't seem to get my head around the super basic things.

I just don't know what to do and I'm finding myself turning my back on the whole PHP language.

Thanking you in advance,

Stu :)

我正在使用此目录结构构建基于PHP的站点 p>

\ n

index.php p>

css strong> p>

    style.css
    li>
  • bootstrap.css li> ul> blockquote>

    包括 strong > p>

    • header.php
      li>
    • footer.php li> ul> blockquote>

      自行车 strong> p>

      • road.php
        li>
      • mountain.php li> ul> blockquote> blockquote> blockquote>

        问题 h2 >

        所以我正在开发 road.php strong>,我显然需要能够链接到 style.css strong>和 bootstrap .css strong>,但是当我在 road.php strong>的开头宣布包含 header.php strong>和 footer.php strong>就好像它找不到样式表一样,网站恢复到默认的20世纪90年代外观。 p>

        我也发现任何形式的链接 在页面上加载404.我只是刚刚开始使用PHP,因为我的网站需要更多的功能,但我似乎无法理解超级基本的东西。 p> \ n

        我只是不知道该怎么做而且我发现自己背弃了整个PHP语言。 p>

        提前感谢你, p>

        Stu:) p> div>

I can't be certain without seeing the actual content of header.php (in perticular the part where you import the stylesheets), but it sounds like you are using a relative path to your stylesheets. Something like <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />. This works fine for index.php, but since the other pages are inside the subfolder bikes, they will be looking for the CSS files in yoursite.com/bikes/css.

The solution is to provide an absolute path. Something like this:

<link rel="stylesheet" type="text/css" href="http://yoursite.com/css/style.css" media="screen" />

This way, it doesn't matter if the page is inside a subfolder (or a subfolder of a subfolder) - it will allways look for the CSS file in the right location.

If you are using multiple domain names, or for some other reason you cannot hardcode the domain name, you can prepend a slash (/) to the path as well:

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

This path is relative to the root of the website, not to the current directory.