【问题标题】:CSS include images relative to the location of the CSS fileCSS 包含相对于 CSS 文件位置的图像
【发布时间】:2015-06-12 13:34:02
【问题描述】:

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

我有一张 CSS 样式的图片:

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

我想在位于同一目录(我将其包含为“mycss.css”)和子目录(我将此文件包含为“../mycss.css”)的 HTML 页面中使用相同的 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 文件相关。

标签: javascript jquery html css


【解决方案1】:

样式表中的所有图像引用都应与 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')

【讨论】:

    【解决方案2】:

    尝试使用您的服务器端代码动态生成带有参数的 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
    

    否则使用 LESS 或 SASS 等条件 CSS

    【讨论】:

      【解决方案3】:

      确保正确调用 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
      

      【讨论】:

      • 确实不需要包含具有绝对路径的文件。
      猜你喜欢
      • 2013-06-22
      • 2018-01-16
      • 1970-01-01
      • 2022-01-25
      • 2016-12-02
      • 1970-01-01
      • 2016-02-22
      • 2019-04-21
      • 2023-03-19
      相关资源
      最近更新 更多