在CSS中,何时/应该使用`url()`函数而不是字符串?

11
什么是两者之间的区别?
.class { background-image: 'bg.png'; }

并且

.class { background-image: url('bg.png'); }

?

Equivalently,

@import 'file.css';

对比。

@import url('file.css');

2
说实话,我认为不使用 url() 是无效的。 - MightyPork
这可能有所帮助。http://jeffreybarke.net/tests/paths/ - knitevision
1
“@import”规则可以不用“url()”来书写 - 这是真的。但我还没有找到不带“url()”的“background-image”属性。http://www.w3.org/TR/CSS21/cascade.html#at-import,http://www.w3.org/TR/css3-background/#the-background-image - user2591042
2个回答

7
根据MDN <image> 文章

These are valid image values:

url(test.jpg)                          The url() function, as long as test.jpg is an image
linear-gradient(to bottom, blue, red)  A <gradient>
element(#colonne3)                     A part of the page, used with the element() function, if colonne3 is an existing CSS id on the page.

These are invalid image values:

cervin.jpg                             An image file must be defined using the url() function.
url(report.pdf)                        The file pointed by the url() function must be an image.
element(#fakeid)                       If fakeid is not an existing CSS id on the page

由于background-image的值必须是一个或多个<image>(或none),因此区别在于background-image: url('bg.png')是有效的,而background-image: 'bg.png'是无效的。

对于@import规范表示它们是等效的:

The '@import' keyword must be followed by the URI of the style sheet to include. A string is also allowed; it will be interpreted as if it had url(...) around it.

The following lines are equivalent in meaning and illustrate both '@import' syntaxes (one with "url()" and one with a bare string):

@import "mystyle.css";
@import url("mystyle.css");

5
在我的测试和研究中,background-image: 'bg.png'; 是完全无效的。根据MDN,background-image 必须定义为关键词或者是<image>,当引用图片文件时必须使用url函数。
但是对于@import来说,url函数是可选的,没有任何区别。
无效:
.class {
    background-image: 'bg.png';
}

有效的:

.class {
    background-image: url('bg.png');
}

有效和相同:


@import 'file.css';
@import url('file.css');

很好。MDN缺少关于@import语句的这一小部分信息。 - adi518
因此,为了保持一致性,在导入时最好也使用 url() - user90726

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接