简体   繁体   中英

I can't link my CSS file to my HTML file. But it is working fine with Live Server. What's wrong?

I had a CSS and a HTML file in the same folder on the desktop. Earlier <link rel="stylesheet" type="text/css" href="style.css" /> was working fine. Now I've made two folders HTML and CSS to separate the files. So, now I use <link rel="stylesheet" type="text/css" href="/CSS/style.css" /> . It works perfectly fine on Live Server in VS Code but when I open index.html normally in a browser, the CSS file does not link, neither do the images which are in the img folder now. I've tried href = "./CSS/style.css" , href="/style.css" . It works ONLY IN LIVE SERVER!!! HELP!

Let's say you have one main directory that has three sub-directories

-MainDirectory
    -HTML
    -CSS
    -Images

Now each file lives inside it's directory...

-MainDirectory
    -HTML
        -index.html
    -CSS
        -style.css
    -Images
        image1.jpg
        image2.jpg

The path for accessing the site is MainDirectory/HTML/index.html

Now, the main file (index.html) needs to use the stylesheet placed in MainDirectory/CSS and the way to achieve this is by manipulating the path to go one directory backwards and from there navigate to css so the code would look like this

<link rel="stylesheet" type="text/css" href="../CSS/style.css" />

What the code does now is that it navigates from HTML to MainDirectory and from there it goes to CSS where it reads the data written in style.css.

The same happens with the images, if you want to access an image you will have to pull the data from ../Images/image1.jpg"

Another way to navigate through the directories is to use a slash / as a starting point so for an example if you are using MainDirectory as your starting point, you can also access the stylesheet like this /CSS/style.css ... This tells the code to start from the very first folder that exists in this path (in our case it is MainDirectory) and from there navigate to where you need to go...

Understand this by creating hyperlinks...

<a href="/style.css">Hover Me!</a>

Place this code in your index.html , then open index.html in your browser and hover over the link.

The path to where this clickable item goes will show in the bottom-left corner of the browser and by being able to see the path you can easily manipulate it... You can see it's starting point and see if you need to go a directory up or not, you can see where you are and where you need to go, play with it, change it until you understand the logic behind it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM