[英]CSS include images relative to the location of the CSS file
有没有办法指示相对于 .css 文件位置的图像路径?
我有一个 CSS 样式的图像:
a[href $= '.pdf']:before {content:url(img/pdf.gif)}
我想在位于同一目录(我将其包含为“mycss.css”)和子目录(我将此文件包含为“../mycss.css”)的 HTML 页面中使用相同的 CSS 文件。
在后一种情况下,显然找不到图像。
编辑:找到了图像,所以问题的其余部分没有意义。
我不想使用绝对路径,因为对于不同的 URL,同一站点显示在不同的级别,例如mysite.example.com
、 example.com/mysite
和example.com/mycompany/mysite
。
有没有办法指示相对于 .css 文件位置的图像路径?
或者,根据存在的图像有条件地包含图像(不要将浏览器与不存在的文件混淆)。 例如,它可能是
a[href $= '.pdf']:before {content:url(img/pdf.gif) url(../img/pdf.gif)}
这样将显示两者之一,但浏览器可能会显示不存在文件所在的占位符。 所以也许它可能是这样的
if exists img/pdf.gif
a[href $= '.pdf']:before {content:url(img/pdf.gif)}
else
a[href $= '.pdf']:before {content:url(../img/pdf.gif)}
样式表中的所有图像引用都应与 CSS 文件相关。
index.html
css/style.css
js/script.js
img/img-1.jpg
img-2.jpg
img-3.jpg
about/index.html
contact/index.html
根据上面的示例,所有在style.css
引用img
目录的图像都是url('../img/*.jpg')
。
尝试使用服务器端代码动态生成带有参数的 CSS
Example: <link rel="stylesheet" type="text/css" href="../mycssservlet?mypathlevel=2">
should generate the CSS on the fly with ../../img/myimg.png
which is 2 time parent relative path
provided the server side program uses the proper content type
否则使用条件 CSS,如 LESS 或 SASS
确保正确调用 CSS 文件。 使用固定的绝对路径:
http://static.example.com/css/style.css
在 CSS 文件中,给出相对于 CSS 的图像路径:
background: url("../img/pic.png");
这适用于:
+ site
|--+ css
| |-- styles.css
| |-- plugin.css
|--+ img
| |-- graphic.png
| |-- img.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.