如何在 css URL 中使用相对/绝对路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5815452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use relative/absolute paths in css URLs?
提问by danidacar
I have a production and development server. The problem is the directory structure.
我有一个生产和开发服务器。问题是目录结构。
Development:
发展:
http://dev.com/subdir/images/image.jpg
http://dev.com/subdir/resources/css/style.css
http://dev.com/subdir/images/image.jpg
http://dev.com/subdir/resources/css/style.css
Production:
生产:
http://live.com/images/image.jpg
http://live.com/resources/css/style.css
http://live.com/images/image.jpg
http://live.com/resources/css/style.css
How can I have a style.css
in css
folder that uses on both servers the same path for the background: url
property? Is there a trick I can use with relative paths?
怎样才可以有一个style.css
在css
文件夹中两台服务器的相同的路径上使用background: url
的财产?我可以使用相对路径的技巧吗?
回答by Kobi
The URL is relative to the location of the CSS file, so this should work for you:
URL 是相对于 CSS 文件的位置,所以这应该适合你:
url('../../images/image.jpg')
The relative URL goes two folders back, and then to the images
folder - it should work for both cases, as long as the structure is the same.
相对 URL 返回两个文件夹,然后返回到images
文件夹 - 只要结构相同,它应该适用于两种情况。
From https://www.w3.org/TR/CSS1/#url:
来自https://www.w3.org/TR/CSS1/#url:
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document
部分 URL 相对于样式表的源进行解释,而不是相对于文档
回答by Garison Piatt
Personally, I would fix this in the .htaccess file. You should have access to that.
就个人而言,我会在 .htaccess 文件中解决这个问题。你应该可以访问它。
Define your CSS URL as such:
像这样定义你的 CSS URL:
url(/image_dir/image.png);
In your .htacess file, put:
在您的 .htacess 文件中,输入:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/
or
或者
RewriteRule ^image_dir/(.*) images/
depending on the site.
取决于网站。
回答by pleasedontbelong
i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.
我遇到了同样的问题......每次我想发布我的 css.. 我必须进行搜索/替换......并且相对路径对我不起作用,因为相对路径从开发到生产不同。
Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like
最后厌倦了搜索/替换,我创建了一个动态 css,(例如 www.mysite.com/css.php)它是一样的,但现在我可以在 css 中使用我的 php 常量。类似的东西
.icon{
background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}
and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.
让它动态化并不是一个坏主意,因为现在我可以使用 YUI 压缩器来压缩它,而不会丢失我的开发服务器上的原始格式。
Good Luck!
祝你好运!