Home > Software design >  How to correctly plug CSS into HTML with absolute path to make picture from CSS working?
How to correctly plug CSS into HTML with absolute path to make picture from CSS working?

Time:01-05

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 page on build-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 ></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 from index.html are loaded with absolute paths, so i was expecting it works from css also.

CodePudding user response:

Actually /folder/css/styles.css also is kinda a relative path. If you are using Windows, some full absolute path should be something like: C:/Folder/image.jpg.

You're doing this just for studies purpose? If yes, I don't think you need to be worry about this.

If you're gonna deploy it in some server, then you gonna have a full absolute path looking something like: https://website.com/images/image.jpg and then you can correctly use the absolute path as something like BASE_PATH/image/image.jpg where BASE_PATH is some variable with the full website link.

CodePudding user response:

Another approach is to set the base in the <head> of your html like this

<base href="https://www.example.com/">

Then all relative url's in your page will be preceded with this url.

folder/img/some.jpg

will become

https://www.example.com/folder/img/some.jpg
  • Related