Five reasons why you should quote attribute values in HTML5
With HTML5, you don’t have to quote attribute values. Until you do.
One of the benefits often touted for HTML5 over XHTML is what I once heard Paul Irish describe as its “loosey goosey” approach to syntax. No longer the strict taskmaster that XHTML was, we can now do all kinds of cool stuff like leave off closing
p tags, and of course, we no longer need to quote attribute values. Think of the bytes saved! The billions of developer hours saved no longer having to type
You can’t always leave off quotes from attribute values. Think about an element with two class attribute values.
<p class=important warning>
Here the browser actually see two attributes,
class=important and a boolean attribute
warning (which it doesn’t understand, but that’s not a problem, making up your own attribute names is what all the kids are doing these days (I’m looking at you Angular!))
So, we need to quote attributes values when they include spaces. But that’s not all. Unquoted attribute values must also not contain any of these characters:
`. Sure, you can have %, or # or £, but no backticks please!
If it does, then quote you must. Think about all sorts of URLs for APIs, or into CMS content, or to blog posts. A
= is very likely to crop up in these URLs. So, why not simply quote all attribute values? One basic rule that will never get you into trouble, and cost you maybe a few dozen bytes a page at most.
BTW, the same rule applies to CSS values that take urls. We only need to use quotes around the URL value when it includes one of the same characters. But why not always again use quotes? Simple pattern, always works. And, the same applies to the value of attribute selectors.
a[attr="attrvalue"] will always be correct.
a[attr=attrvalue] won’t be if attrvalue contains spaces or one of our magic characters.
You could try to remember all these rules – go for it! But sometimes it just pays to be strict.