简体   繁体   中英

Solution to relative path to image in CSS file depending on what file that includes it

Lets say I have a filestructure:

index.html
css/styles.css
images/paper.gif
subfolder/index.html

css file called styles.css, located in a folder called css/styles.css containing

.image{
    background-image: url("images/paper.gif");
    background-color: #cccccc;
}

If I include this file in a index.html located in root directory the image will show.

Now lets say I have another folder called subfolder/index.html and want to inlcude that css ../css/styles.css file then that url to the image wont work since the css file is expecting that there would be a folder called images in "subfolder" with a file in it. So in order to avoid having to declare 2 classes containing the same code, is there another way of dealing with this problem?

Thanks in advance.

It should work for root and sub folders index file..

.image{
background-image: url("../images/paper.gif");
background-color: #cccccc;
}

But check path of included CSS in Index file.

it should be For Root index file

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

and for sub folder index file.

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

The only way is with absolute paths. This means that in your CSS you must define an absolute path for your images, for example:

 background-image: url(/images/image.png);

What's the problem? You need to know the absolute path where your folders are. For example, if you have this URL: http://localhost/myFolder/images/image.png , your CSS will be:

 background-image: url(/myFolder/images/image.png);

But when you upload it to a production server like this: http://myserver.com/images/image.png , your CSS must to change to something like this:

 background-image: url(/images/image.png);

So the best way is to develop in the same environment that your production server. This will be with the URL http://localhost/images/image.png (develop) and http://myserver.com/images/image.png (production).

Another way is to making friendly URLs, that avoids to you to make custom folders, and you can have all in one folder and the URLs will be rewrited by the server.

Good luck.

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