htmlcsshrefabsolute-pathlocal-files

How to write out the absolute path of a local file correctly when linking css file to html?


I'm a complete beginner of html/css.

I use PHP to include the same head section in different webpages. There is a href link in the head section linking to an external css. file which styles the layout of multiple webpages.

Since the different webpages locate in different subfolders in the root folder, I have to use the absolute path to link the css. file, and here comes the problem: I don't know how to write it correctly.

When I use relative path for each individual webpage, the link works fine, but when I tried to use the absolute path, it simply doesn't work.

I have tried:

1.href="file:///C:\xampp\htdocs\root\styles\style.css"

2.href="file:///C:/xampp/htdocs/root/styles/style.css"

3.href="file://C:/xampp/htdocs/root/styles/style.css"

4.href="C:/xampp/htdocs/root/styles/style.css"

5.href="c:/xampp/htdocs/root/styles/style.css"

Here is the beginning part of the code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <?php include('common/head.php') ?>
    <title>Home</title>
  </head>

and this is the head section:

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="file:///C:\xampp\htdocs\root\styles\style.css">

Solution

  • I guess this is a popular misconception between server-side and client-side execution context.

    1. The webserver provides an html document for http://localhost/whatever/index.htm
    2. Your browser reads that document and it's href-attributes. It tries to download the linked files too.
      • href="styles/style.css" a relative path. The browser will request the file at http://localhost/whatever/styles/style.css
      • href="/styles/style.css" a kind-of-absolute path. The browser will request the file at the root of the servers url http://localhost/styles/style.css
      • href="http://localhost/foobar/styles/style.css" an absolute path. The browser will try to download exactly from there.
      • href="file:///C:\...." a local path on your system. The server has nothing to do with it. The page may only work on your own system not when other people access it through the server from other computers.

    Your browser should come some development tools. You can inspect what your browser is requesting and what your server is responding with that tools.

    The answer is: use relative or kind-of-absolute urls here.