Search code examples
cssvercel

Why is vercel not rendering my css file while deploying in the web page?


While running on local host, the output is as expected.

Output on localhost

But after updating the styles in GitHub, and then later deploying on vercel for this URL: https://varshaa.vercel.app/JSbasics/counter, the webpage looks like this.

Output after deploying on vercel

This is my GitHub repo. Please let me know where have I done wrong. https://github.com/shettyvarshaa/varshaashetty/tree/main/JSbasics/counter

I tried to add the CSS and HTML file onto a separate folder, but it did not work.


Solution

  • I can show you a magic trick, click here: https://varshaa.vercel.app/JSbasics/counter/

    How can it be?

    When accessing the HTML page at https://varshaa.vercel.app/JSbasics/counter/index.html (or even without index.html, but with the last slash in place), the CSS file style.css is correctly loaded because the relative path <link rel="stylesheet" href="style.css" /> correctly resolves to https://varshaa.vercel.app/JSbasics/counter/style.css.

    However, when accessing the URL without the trailing slash (https://varshaa.vercel.app/JSbasics/counter), the browser treats this as a file, not a directory. Consequently, relative paths are resolved relative to the parent directory of the URL. Therefore, the browser attempts to load the CSS file from https://varshaa.vercel.app/JSbasics/style.css, which is incorrect and results in the CSS not being applied.

    To ensure that the CSS file is correctly loaded regardless of the URL format, you should use an absolute path in the tag. This ensures that the browser always requests the CSS file from the correct location, regardless of how the URL is formatted.

    <link rel="stylesheet" href="/JSbasics/counter/style.css" />
    

    Also: your git repo is private, people cannot see your code.