Search code examples
htmlcsswebstormrelative-pathabsolute-path

How to correctly plug CSS into HTML with absolute path to make picture from CSS working?


It might sound silly, but I am trying to understand this.

When I plugged CSS with absolute path - picture/fonts are not loading (404).

I test a page on the built-in WebStorm server (2022.3) through Chrome browser.

[i just heard absolute paths are better, that is why]

What did I miss?

Here is an example:

file structure

css-pract[root]/
-folder/
--css/
---styles.css
--img/
---some.jpg
-index.html

index.html

<!doctype html>
<html lang="ru">
<head>
  <link rel="stylesheet" href="/folder/css/styles.css">
</head>
<body>
  <div class="has-bg"></div>
</body>
</html>

styles.css

.has-bg {
  background: url("/folder/img/some.jpg");
}

It works when I do relative: <link rel="stylesheet" href="css/styles.css">

Also, the <img> from index.html are loaded with absolute paths, so I was expecting it to work from css also.


Solution

  • I've tied to replicate your folder structure and both relative and absolute paths worked for me.

    You need to give the div with class "has-bg" a height, however, in order to see the background image. Perhaps you forgot to do this for the absolute paths?

    Relative paths

    in index.html:

    <link rel="stylesheet" href="./folder/css/styles.css" />
    

    in styles.css:

    background: url("../img/some.jpg");
    

    Absolute paths

    in index.html:

    <link rel="stylesheet" href="/folder/css/styles.css" />
    

    in styles.css:

    background: url("/folder/img/some.jpg");