Is quoting the value of url() really necessary?

后端 未结 7 2056
情话喂你
情话喂你 2020-11-22 09:40

Which of the following should I use in my stylesheets?

/* Example #1: */ background-image: url(image.png);
/* Example #2: */ background-image: url(\"image.pn         


        
7条回答
  •  孤城傲影
    2020-11-22 10:28

    Here is what the W3 CSS 2.1 specification says:

    The format of a URI value is 'url(' followed by optional white space followed by an optional single quote (') or double quote (") character followed by the URI itself, followed by an optional single quote (') or double quote (") character followed by optional white space followed by ')'. The two quote characters must be the same.

    Source: http://www.w3.org/TR/CSS21/syndata.html#uri

    So all of the 3 examples you proposed are correct, but the one that I would choose is the first one because you use less characters and hence the resulting CSS file will be smaller, resulting in less bandwidth usage.

    This might feel like that is not important, but high traffic websites prefer to save bandwidth and over lots of css files, and url references in them it make sense to choose the option that make the file smaller... Even because there is no advantage in not doing so.

    Note: you might have to escape characters if urls contain parentheses, commas, white space characters, single quotes or double quotes. This might make the url longer than just using quotes (which need less escaping). Hence you might want to serve a Css file with urls with no quotes only when the overhead of escaping does not make the url longer than just using quotes (which is very rare).

    However I would not expect any human being to even consider these edge cases... A Css optimizer would handle this for you... (but sure you need to know about all of this if you are actually writing a css optimizer :P)

提交回复
热议问题