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

chh*_*vey 6 css url

有什么区别

.class { background-image: 'bg.png'; }
Run Code Online (Sandbox Code Playgroud)

.class { background-image: url('bg.png'); }
Run Code Online (Sandbox Code Playgroud)

?

同样,

@import 'file.css';
Run Code Online (Sandbox Code Playgroud)

对比

@import url('file.css');
Run Code Online (Sandbox Code Playgroud)

Ori*_*iol 7

According to MDN <image> article:

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.
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Since the value of background-image must be one or more <image> (or none), the difference is that background-image: url('bg.png') is valid and background-image: 'bg.png' is invalid.

For @import, the spec says they are equivalent:

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");
Run Code Online (Sandbox Code Playgroud)


Ale*_*ara 5

In my testing and research, background-image: 'bg.png'; is completely invalid. According to MDN, background-image must be defined as a keyword or an <image> which when referencing an image file must use the url function.

For @import however, the url function is optional and there is no difference.


Invalid:

.class {
    background-image: 'bg.png';
}
Run Code Online (Sandbox Code Playgroud)

Valid:

.class {
    background-image: url('bg.png');
}
Run Code Online (Sandbox Code Playgroud)

Valid and Identical:

@import 'file.css';
@import url('file.css');
Run Code Online (Sandbox Code Playgroud)