CSS 包括相对于 CSS 文件位置的图像

CSS include images relative to the location of the CSS file

本文关键字:CSS 图像 位置 文件 包括 相对于      更新时间:2023-09-26

有没有办法指示相对于.css文件位置的图像路径?

我有一个 CSS 风格的图像:

a[href $= '.pdf']:before {content:url(img/pdf.gif)}

我想在位于同一目录的 HTML 页面中使用相同的 CSS 文件(我将其包含在"mycss.css")和子目录中(我将此文件包含在"../mycss.css")。

在后一种情况下,显然找不到图像。

编辑:图像被发现,所以其余的问题没有意义。

我不想使用绝对路径,因为对于不同的 URL,同一站点显示在不同的级别,如mysite.example.comexample.com/mysiteexample.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.cssimg目录的所有图像都将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