CSS 背景图像路径问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2405333/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:40:41  来源:igfitidea点击:

CSS Background-Image Path Issues

cssbackground-image

提问by Deacon

In amongst my CSS I have the following:

在我的 CSS 中,我有以下内容:

#framecontentTop{
position: absolute;
top: 0;
left: 120px;
right: 0;
height: 100px;
overflow: hidden;
background-image: url(/Users/myname/Website Project/logo.jpg);
color: white;
}

Where the path to the image I want to use as the background-image is /Users/myname/Website Project/logo.jpg

我想用作背景图像的图像路径是 /Users/myname/Website Project/logo.jpg

However, when I put in my div with the ID framecontentTop, it doesn't show the image (or indeed anything) as the background. There are no other divs in the CSS to conflict with it, and when I set the background for framecontentTop to a colour or keep it as an image but put the URL as some random image online, it loads it fine. So I can only assume the problem is with how I have specified the path to the image - can anyone see what I have done wrong here?

但是,当我将 ID 为 framecontentTop 的 div 放入我的 div 时,它不会将图像(或任何东西)显示为背景。CSS 中没有其他 div 与它发生冲突,当我将 framecontentTop 的背景设置为一种颜色或将其保留为图像但将 URL 作为一些随机图像在线放置时,它可以正常加载。所以我只能假设问题在于我如何指定图像的路径 - 谁能看到我在这里做错了什么?

Many thanks

非常感谢

回答by Nick Craver

If you have any special characters, they should be escaped, or in the case of white-space, at least quoted, like this:

如果你有任何特殊字符,它们应该被转义,或者在空格的情况下,至少引用,像这样:

background-image: url("/Users/myname/Website Project/logo.jpg");

You can see the W3C Specfor the full requirements.

您可以查看W3C 规范以了解完整要求。

Some characters appearing in an unquoted URI, such as parentheses, commas, white space characters, single quotes (') and double quotes ("), must be escaped with a backslash so that the resulting URI value is a URI token: '(', ')', '\,'.

出现在未加引号的 URI 中的某些字符,例如括号、逗号、空格字符、单引号 (') 和双引号 ("),必须使用反斜杠进行转义,以便生成的 URI 值是 URI 标记:'(' , ')', '\,'。

回答by Pekka

You are using an absolute path that will always resolve to the same URL on your server. If that works when you put it in element A, but doesn't work in element B, chances are the problem is not with the URL, but another backgroundor background-imagesetting interfering.

您使用的绝对路径将始终解析为您服务器上的相同 URL。如果将它放在元素 A 中时有效,但在元素 B 中不起作用,则问题很可能不在于 URL,而是另一个backgroundbackground-image设置干扰。

I would use Firebug's "Inspect Element" function to find out whether there is another background setting taking precedence.

我会使用 Firebug 的“检查元素”功能来确定是否有另一个背景设置优先。

URLs with spaces should always be in quotes by the way:

顺便说一下,带有空格的 URL 应该总是用引号引起来:

background-image: url("/Users/myname/Website Project/logo.jpg");