问题
I am storing style sheets in {root}/styles while images in {root}/images for a website. How do I give the path in the style sheets to go look in the images directory for the specified images?
e.g. In background-image: url(\'/images/bg.png\');
回答1:
Use ..
to indicate the parent directory:
background-image: url('../images/bg.png');
回答2:
Use ../
:
background-image: url('../images/bg.png');
You can use that as often as you want, e.g. ../../images/
or even at different positions, e.g. ../images/../images/../images/
(same as ../images/
of course)
回答3:
Here is all you need to know about relative file paths:
Starting with
/
returns to the root directory and starts thereStarting with
../
moves one directory backward and starts thereStarting with
../../
moves two directories backward and starts there (and so on...)To move forward, just start with the first sub directory and keep moving forward.
Click here for more details!
回答4:
In Chrome when you load a website from some HTTP server both absolute paths (e.g. /images/sth.png
) and relative paths to some upper level directory (e.g. ../images/sth.png
) work.
But!
When you load (in Chrome!) a HTML document from local filesystem you cannot access directories above current directory. I.e. you cannot access ../something/something.sth
and changing relative path to absolute or anything else won't help.
回答5:
Supposing you have the following file structure:
-css
--index.css
-images
--image1.png
--image2.png
--image3.png
In CSS you can access image1
, for example, using the line ../images/image1.png
.
NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.
来源:https://stackoverflow.com/questions/4810927/how-to-go-up-a-level-in-the-src-path-of-a-url-in-html