Reputation: 1
I built an Edge Ledger website, did the HTML and CSS styling using VS Code. When I run it with live server it works fine, the CSS styling I did is implemented but if I just go to the root folder and open the index.html file without using VS Code to run it, it just shows the HTML element without the styling. Can anyone help?
I tried opening the index file without VS Code, it just loads the HTML file without the CSS.
When I run this with live server on VS Code the CSS styling I did is applied to the index.html page
What could be the problem?
Upvotes: 0
Views: 1748
Reputation: 5926
The issue with opening an HTML file directly is that now your computer's own hard drive is the "server" serving the files. As such, the browser asks your computer for your CSS files at the directory /css
, the /
indicating the root directory of your whole file-system.
For your computer, there's a couple of issues with that. Routes starting with /
are usually used on UNIX-based systems (think of MacOS or Linux distros like Ubuntu), but since you're using Windows, that type of a directory or path won't resolve to anything. And even if you were using MacOS or Linux, you most likely would not have your CSS files in /
, as that would be like having them right under C:/
in Windows.
This is the reason why when serving the HTML files over a proper server, the /
path is correctly resolved, as there /
indicates the root of your web server's directory, and not the root of your file system.
If you'd like to keep your code as-is and you have either Python or Node.js installed locally on your machine, you can use either of them to spin up a lightweight HTTP server to act as a static file server.
# Python 2.x
python -m SimpleHTTPServer
# Python 3.x
python3 -m http.server
# Node.js with npm
npx serve
Now visiting http://localhost:8080 (or whatever port your terminal tells you), should serve up your HTML file and correctly resolve the CSS asset paths.
You can find a large list of other static servers for different languages here: https://gist.github.com/willurd/5720255
Another solution is to remove the /
prefix from your asset paths, making them relative paths to the index.html
file. Note that this could lead to other unexpected scenarios in the future, for example if your index.html file is also served for an /about
page, then the CSS asset paths would now resolve to /about/css
instead of /css
(as the css/...
path is now relative to the current path and will be appended to it). So even though this is a cheap and quick fix locally, it's not considered the best practise.
Upvotes: 1