Is it correct to use single quotes for HTML attrib

2019-01-10 21:38发布

Recently I've been seeing a lot of this:

<a href='http://widget-site-example.com/example.html'>
    <img src='http://widget-site-example.com/ross.jpg' alt='Ross&#39;s Widget' />
</a>

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

15条回答
我只想做你的唯一
2楼-- · 2019-01-10 22:24

What's against single quotes?

You can have single/double quotes all over your html code without any problem, as long as you keep the same quoting style inside a current tags ( many browser won't complain even about this, and validation just want that if you start with a quote, end with the same, inside the same propriety )

Free support to random quoting styles!!! (yay ;D )

查看更多
趁早两清
3楼-- · 2019-01-10 22:27

Single quotes are perfectly legal in (X)HTML. Using a backslash to escape them, on the other hand, isn't. <img src='http://widget-site-example.com/ross.jpg' alt='Ross\'s Widget' /> is an image with the alt text "Ross\", and empty s and Widget/Widget' attributes. The correct way of escaping an apostrophe in HTML is &#39;.

查看更多
\"骚年 ilove
4楼-- · 2019-01-10 22:30

If you want to the to be valid or then both or will work for attributes. HTML4 can be validated here: https://validator.w3.org/

If you are supporting only modern browsers ( and higher) then you can use the syntax which allows single quotes, double quotes, and no quotes (as long as there are no special characters in the attributes' value). HTML5 can be validated here: https://validator.w3.org/nu

查看更多
叛逆
5楼-- · 2019-01-10 22:35

I know this is an old thread, but still very much relevant.

If you want control over quotes in your generated HTML, you can use the sprintf() function in PHP (and similar calls available in many other languages):

$html = sprintf('<a href="%s">%s</a>', $url, $text);

Using sprintf() allows the format string to be easily modifiable by retrieving it from a database or configuration file, or via translation mechanisms.

It is very readable, and allows either double or single quotes in the generated HTML, with very little change and never any escaping:

$html = sprintf("<a href='%s'>%s</a>", $url, $text);
查看更多
Root(大扎)
6楼-- · 2019-01-10 22:36

Someone may use it in PHP to avoid escaping " if they're using double quoted string to parse variables within it, or to avoid using string concatenation operator.

Example:

echo "<input type='text' value='$data'/>";

instead of

echo "<input type=\"text\" value=\"$data\" />";

or

echo '<input type="text" value="' . $data . '" />';

Nowadays I always stick to using double quotes for HTML and single quotes for Javascript.

查看更多
Explosion°爆炸
7楼-- · 2019-01-10 22:37

It's certainly valid to use single quotes (HTML 4.01, section 3.2.2). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.

查看更多
登录 后发表回答