292

I've always used single quotes when writing my HTML by hand. I work with a lot of rendered HTML which always uses double quotes. This allows me to determine if the HTML was written by hand or generated. Is this a good idea?

What is the difference between the two? I know they both work and are supported by all modern browsers but is there a real difference where one is actually better than the other in different situations?

animuson
  • 53,861
  • 28
  • 137
  • 147
ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
  • 2
    Related: http://stackoverflow.com/questions/273354/html-single-quotes-a-problem and http://stackoverflow.com/questions/242766/when-did-single-quotes-in-html-become-so-popular. – ЯegDwight Mar 03 '10 at 16:45
  • 8
    To answer the question about whether using single- vs double-quotes as means to determine hand-written vs generated HTML, no it's probably not a good idea. While code that is *inconsistent* (uses single in some places, double in others) is probably hand-written, I'm sure plenty of people (including myself) use double-quotes everywhere, but our code certainly isn't computer-generated ;) – Doktor J Feb 20 '12 at 12:16
  • @Aito's answer is correct indeed and should be accepted ... Personally, I use single quotes for short attributes like single keywords / tags, URL and references; anything that is not intended to be read by human, actually. For longer texts, or anything that might include spaces or single quotes / apostrophes - as content, I use double quotes. It just a matter of your style (or the style guide you use) – cedbeu Feb 27 '13 at 15:54
  • 1
    checkout 10 major websites and see what the majority of them use, like stackoverflow, youtube/google, wikipedia. So far I have trouble finding major websites that use single-quotes. – Timo Huovinen Nov 02 '15 at 12:55
  • so many websites use double quotes for HTML, so please use double quotes.. it also affects searching in HTML documents, single quotes and double quotes take effect.. I standardized using double quotes.. – Fauzan Edris Nov 05 '21 at 09:22

16 Answers16

422

The w3 org said:

By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39). Single quote marks can be included within the attribute value when the value is delimited by double quote marks, and vice versa. Authors may also use numeric character references to represent double quotes (") and single quotes ('). For double quotes authors can also use the character entity reference ".

So... seems to be no difference. Only depends on your style.

Blixt
  • 49,547
  • 13
  • 120
  • 153
Aito
  • 6,812
  • 3
  • 30
  • 41
  • 46
    and being consistent (either with ' or ") will most probably result in higher compression rates in case you serve compressed (gzip, deflate) pages – cherouvim Mar 03 '10 at 16:53
  • 3
    @Aito, that's for SGML. For HTML, not all attribute values need to be delimited – Pacerier Jan 26 '13 at 08:30
  • 2
    @Pacerier, you're right. More information about your comment in http://en.wikipedia.org/wiki/Standard_Generalized_Markup_Language#HTML – Aito Jan 28 '13 at 16:38
  • 1
    Didn't know we can use ' or " My html tokenizer for the LIVEditor project must handle that... – Edwin Yip May 02 '13 at 11:56
  • 8
    I suggest though single over double -- Why use two when one can do the job. – Ujjwal Singh Jun 22 '14 at 19:00
  • 3
    I prefer single quotes whenever I can because it only takes one keypress to enter them, whereas with a double quote you have to depress shift. – JustinParker May 29 '15 at 16:31
  • While the conclusion of 'no difference' is right, HTML is *not* SGML. For example HTML 5 allows any attribute to have unquoted value: http://www.w3.org/html/wg/drafts/html/master/syntax.html#attributes-2 – Sheepy Jun 08 '15 at 05:11
  • 7
    @cherouvim higher compression rates? We're talking 1 byte.. maybe 2? LOL. I don't think that's relevant. – John Hunt Jan 15 '16 at 14:42
  • 15
    @JohnHunt: Just did a quick test on a 1823 bytes js file (a random Backbone Model from a random application). The gzip output if all of the quotes are the same (either `'` or `"`) was 809 bytes. Mixing them pushed the output up to 829 bytes. This may be irrelevant to you but that doesn't mean that it's irrelevant to everybody. – cherouvim Jan 15 '16 at 15:00
  • 2
    +1 for testing, however 20 bytes on even on a *very* slow GPRS connection would take < 1 millisecond. This is nowhere near noticeable. Anyone working to this level of optimisation probably shouldn't be using HTML or an SGML based markup. – John Hunt Jan 15 '16 at 15:06
  • 2
    In fact, 20 bytes in pretty much any area in 2016 is fairly irrelevant. 20 bytes on a ZX80 was fairly irrelevant 33 years ago.. – John Hunt Jan 15 '16 at 15:07
  • 2
    @johnhunt Declaring 20 bytes as irrelevant is a bad assumption. Cutting down on your bandwidth bill by 1-2% might significantly impact the bottom line for some companies. – Jay Oct 07 '17 at 01:50
  • 7
    @Jacob Think more like 0.0001%, at most. In the real world this difference isn't worth anyone's time to even think about unless people are using morse code to transfer the data with a flashlight. 20 bytes is 160 bits. To put this into perspective, in 1962 a Bell 103 or V.21 modem could transfer this in about half a second. In 1991 with a 14.4k modem it'd take a 90th of a second. Today, on the web? It's irrelevant. Period. Integrated specialised north-pole or space comms stuff, maybe not. The web, yes, irrelevant. – John Hunt Oct 09 '17 at 09:14
  • Sources: https://en.wikipedia.org/wiki/Modem#List_of_dialup_speeds - quite interesting. Notice how gosh darn quick everything is now? :) – John Hunt Oct 09 '17 at 09:15
  • 2
    @John Come on, you're being a bit too flippant. Yes, 20 bytes is not very much, but the test was on a *single* file of 1823 bytes. Obviously, web pages are reading considerably more than just one file. At the moment, this page is over 219777 bytes. 2% would save almost 5000 bytes. Is that still irrelevant? If it were tedious to ensure consistency, I could see your argument. But, search-and-replace or just being consistent from the start....not much effort for *some* gain. So, this is a case of "something for nothing" (better compression for consistency with quote characters.) – Zonker.in.Geneva May 13 '18 at 14:32
  • 1
    Yes I am being a bit flippant, but it's based in reality. Theoretically it's an interesting discussion though. Of course if you can make savings and you have the time and budget then go for it I guess – John Hunt May 13 '18 at 14:49
  • 4
    If one says "oh it's such a low potential, probably irrelevant" to a hundred "probably irrelevant" things, death of a thousand needles ensues. Within reasonable effort, everything you can save is worth saving IMO. – CONTRACT SAYS I'M RIGHT Jun 29 '18 at 08:06
  • 2
    An accrual of negligible gains is time poorly spent. Pick one: tweak your caching policy, crush PNGs, don't bundle JQuery just to query selectors... There are so many ways so save so much more; who would walk past a money tree to bend over and pick up pennies? – snarf Jul 25 '20 at 18:35
  • paying an engineer to find and change all double to single quotes isn't likely to be money well spent. the math on the bandwidth savings only looked at the content and disregarded all the tcp/ip overhead meaning delta even more negligible. i'm one of those people that use single quotes because it's slightly lazier than using doubles. plus, uses less ink when printing. :) – keithpjolley Dec 01 '21 at 22:37
  • @keithpjolley: manyally formating code has been dead for years now thanks to modern editors/IDEs and https://prettier.io/ – cherouvim Feb 20 '22 at 05:41
  • 1
    @JohnHunt now multiply 20 bytes by 1 billion requests by day (Youtube example) and we get quite a bandwidth difference. Never underestimate a byte or even a bit. – Hefaistos68 Feb 24 '22 at 11:50
  • I am just popping in to say that this is the most ricer thread that I have seen on SO ever. Do you also run Gentoo? https://www.shlomifish.org/humour/by-others/funroll-loops/Gentoo-is-Rice.html – kbuilds Oct 04 '22 at 19:12
85

I use " as a top-tier and ' as a second tier, as I imagine most people do. For example

<a href="#" onclick="alert('Clicked!');">Click Me!</a>

In that example, you must use both, it is unavoidable.

Bennett
  • 1,007
  • 4
  • 15
  • 29
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
43

Quoting Conventions for Web Developers

The Short Answer

In HTML the use of single quotes (') and double quotes (") are interchangeable, there is no difference.

But consistency is recommended, therefore we must pick a syntax convention and use it regularly.

The Long Answer

Web Development often consists of many programming languages. HTML, JS, CSS, PHP, ASP, RoR, Python, etc. Because of this we have many syntax conventions for different programming languages. Often habits from one language will follow us to other languages, even if it is not considered "proper" i.e. commenting conventions. Quoting conventions also falls into this category for me.

But I tend to use HTML tightly in conjunction with PHP. And in PHP there is a major difference between single quotes and double quotes. In PHP with double quotes "you can insert variables directly within the text of the string". (scriptingok.com) And when using single quotes "the text appears as it is". (scriptingok.com)

PHP takes longer to process double quoted strings. Since the PHP parser has to read the whole string in advance to detect any variable inside—and concatenate it—it takes longer to process than a single quoted string. (scriptingok.com)

 

Single quotes are easier on the server. Since PHP does not need to read the whole string in advance, the server can work faster and happier. (scriptingok.com)

Other things to consider

  1. Frequency of double quotes within string. I find that I need to use double quotes (") within my strings more often than I need to use single quotes (') within strings. To reduce the number of character escapes needed I favor single quote delimiters.
  2. It's easier to make a single quote. This is fairly self explanatory but to clarify, why press the SHIFT key more times than you have to.

My Convention

With this understanding of PHP I have set the convention (for myself and the rest of my company) that strings are to be represented as single quotes by default for server optimization. Double quotes are used within the string if a quotes are required such as JavaScript within an attribute, for example:

<button onClick='func("param");'>Press Me</button>

Of course if we are in PHP and want the parser to handle PHP variables within the string we should intentionally use double quotes. $a='Awesome'; $b = "Not $a";

Sources

Single quotes vs Double quotes in PHP. (n.d.). Retrieved November 26, 2014, from http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP

Corwin Newall
  • 508
  • 8
  • 18
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32
  • 6
    The single quote vs double quote performance difference in PHP was known to be zero years before you answered this question: https://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html – Conor Mancone Oct 20 '17 at 16:12
  • 1
    You find more double quotes than single quotes within your strings? Interesting. I can't remember the last time I had a double quote in my strings. – Zonker.in.Geneva May 13 '18 at 14:36
  • Constantly. In the past 10 years as a full-stack developer i find myself needing to use double quotes within a string 10x more often than single quotes. The most common example for JavaScript is attribute selectors ONLY work with double quotes so `document.querySelector("[name^='myname']")` does not work at all while `document.querySelector('[name^="myname"]')` works perfectly. – Dustin Poissant May 14 '18 at 14:43
  • 2
    @DustinPoissant WHAAAT?? On which browser?? – Mr Lister Nov 28 '18 at 21:00
20

If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of repetitive strain injury.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
stko
  • 573
  • 3
  • 7
  • 2
    well, at least on the Galactic Common layout. (hush-hush) – n611x007 Feb 13 '14 at 14:51
  • 2
    What has the risk of RSI and the number of keystrokes got to do with coding standards? – Dib Aug 11 '14 at 10:41
  • so many opinions that there is no difference between single and double quotes, but only one that clarifies that the number of keystrokes differs a factor of TWO. And we need many quotes. May I add with the suggestion that it will perhaps require more neurons to fire for the pattern recognition of a double quote in our brain? – Roland Feb 23 '17 at 10:27
  • I disagree. Displayed characters and the way you input them are two separate things. The fact that you, personally, may like a certain input mechanism requiring holding down the shift key to obtain a double quote does not mean that the OP likes to use the same input mechanism. – Damien L Sep 08 '21 at 14:10
  • Not gonna lie, RSI is a main reason why I use single-quotes whenever I can. Less pinky pain! – JoePC Nov 08 '21 at 23:08
15

Actually, the best way is the way Google recommends. Double quotes: https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Quotation_Marks#HTML_Quotation_Marks

See https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Validity#HTML_Validity Quoted Advice from Google: "Using valid HTML is a measurable baseline quality attribute that contributes to learning about technical requirements and constraints, and that ensures proper HTML usage."

Stuart
  • 193
  • 1
  • 10
  • The grand majority of websites I encountered so far, including stackoverflow, use double quotes, I think consistency across the web is for the better, so the correct answer IMHO is also "double quotes". – Timo Huovinen Nov 02 '15 at 12:49
  • 2
    But why!? Why `"` over `'`!?? – San Aug 23 '16 at 19:00
  • 2
    @San Consistency, mostly. It follows the American English standard that double quotes are for quotes and single quotes are for subquotes. – Nielsvh Aug 17 '17 at 23:01
11

In HTML I don't believe it matters whether you use " or ', but it should be used consistently throughout the document.

My own usage prefers that attributes/html use ", whereas all javascript uses ' instead.

This makes it slightly easier, for me, to read and check. If your use makes more sense for you than mine would, there's no need for change. But, to me, your code would feel messy. It's personal is all.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Why does it need to be used consistently? Just for readability? – timetofly Mar 15 '13 at 17:59
  • Because it's easier to avoid mistakes that way. – David Thomas Mar 15 '13 at 18:04
  • 2
    I often have the attributes use `"` as well, but other times I'm writing code in PHP code where I would prefer the `echo`'s use `"`'s in order to allow parsing. Any html attributes within this echo is more readable if using `'`'s. Sure it's not consistent, but it's much easier without all the backslashes. – timetofly Mar 15 '13 at 18:14
  • 3
    Whatever works for you is fine; being consistent doesn't mean 'always do X' it just means 'in situation X do it this way,' consistency can be context-aware; and is best-used as such. – David Thomas Mar 15 '13 at 18:16
6

I know LOTS of people wouldn't agree, but this is what I do and I really enjoy such a coding style: I actually don't use any quote in HTML unless it is absolutely necessary.

Example:

<form method=post action=#>
<fieldset>
<legend>Register here: </legend>
  <label for=account>Account: </label>
  <input id=account type=text name=account required><br>
  <label for=password>Password: </label>
  <input id=password type=password name=password required><br>
...

Double quotes are used only when there are spaces in the attribute values or whatever:

<form class="val1 val2 val3" method=post action=#>
  ...
</form>
Randy Tang
  • 4,283
  • 12
  • 54
  • 112
  • 1
    Is there a reason behind? Or you just "really enjoy such coding style"? – Bugs Bunny Jun 09 '15 at 15:04
  • 4
    Without quotes the HTML looks a lot cleaner (and the file size is a little bit smaller). That's the only reason and nothing else. Furthermore, I really can't see the point to require **every** attribute to have quotes. Why can't it just be omitted to save the trouble? Even w3.org accepts unquoted attribute values (http://www.w3.org/TR/html-markup/syntax.html#syntax-attr-unquoted). **Simple is better than complex.** Is it some kind of religion to have quotes? – Randy Tang Jun 09 '15 at 16:40
  • 6
    Nope, no religion that I am aware of. I've been around HTML for quite some time and never seen your style used before ... therefore I asked. – Bugs Bunny Jun 10 '15 at 07:06
  • Yeah, I've been working on HTML for a few years too, and was really tired of typing so many double quotes. It doesn't make sense and I finally decided to liberate myself. Just like Python guys decided to ditch the semicolons. Am I the only one doing such a thing in the HTML world? ;-) – Randy Tang Jun 10 '15 at 07:40
  • `
    ` should be `
    `
    – deW1 Jun 17 '15 at 20:21
  • @deW1 html5 uses `
    ` @yltang52 I agree, simpler is better, but keep in mind that just adding double quotes all the time requires less thinking and more monotone typing
    – Timo Huovinen Nov 02 '15 at 12:47
  • It's not valid XHTML though so it will not be readable by an XML parser AFAIK. What you think is cleaner, to others may be less clean. This syntax looks strange to me. I've tried doing it myself as well, but it feels dirty doing it. It is safer to stick to convention because you have more assurance that what you're writing is supported. What I will say about your desire to write HTML in this way is that you are perhaps not going far enough. If you want to write like this, you might as well start developing with an HTML pre-processor instead like Slim. – Jonathan Jan 16 '16 at 17:35
  • @SugarTang What are all the cons you've faced so far with this style? Any other tools complained that your HTML is incompatible? – San Sep 27 '17 at 19:06
  • 2
    Also, HTML minifiers strip unnecessary quotes too. – Nimrod Oct 27 '17 at 17:52
  • 2
    The problem with leaving out quotes around attribute values is that different standards have different lists of characters which need to be quoted. For example, HTML4 said only values consisting of letters, digits, dashes and dots could go unquoted, but HTML5 says anything goes except spaces and " ' ` < = >, so you should be careful, especially with older browsers! – Mr Lister Nov 28 '18 at 21:18
  • This does not work for tags that must contain whitespace in them. Such that
    would be interpreted as
    . Notice that bar is an attribute not a second class value as intended.
    – Itanex Mar 28 '19 at 22:48
  • For vue, it makes it easier to see if you're binding string / JS expression or a single variable. I have a rule for myself to not use quotes for single variable. And this also helps ensure I avoid JS expression in the template as much as possible. – Pui Ho Lam Mar 22 '23 at 23:07
5

Using double quotes for HTML

i.e.

<div class="colorFont"></div>

Using single quotes for JavaScript

i.e.

$('#container').addClass('colorFont');
$('<div class="colorFont2></div>');
Alan Dong
  • 3,981
  • 38
  • 35
3

I had an issue with Bootstrap where I had to use double quotes as single quotes didn't work.

class='row-fluid' made the last <span> fall below the other <span>s, rather than sitting nicely beside them on the far right. class="row-fluid" worked.

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
MikeP
  • 161
  • 1
  • 1
  • 7
2

It makes no difference to the html but if you are generating html dynamically with another programming language then one way may be easier than another.

For example in Java the double quote is used to indicate the start and end of a String, so if you want to include a doublequote within the String you have to escape it with a backslash.

String s = "<a href=\"link\">a Link</a>"

You don't have such a problem with the single quote, therefore use of the single quote makes for more readable code in Java.

String s = "<a href='link'>a Link</a>"

Especially if you have to write html elements with many attributes.(Note I usually use a library such as jhtml to write html in Java, but not always practical to do so)

Paul Taylor
  • 13,411
  • 42
  • 184
  • 351
  • Did two internships on servlets. I was analyzing my code and only now i started realizing the reality on double quotes, single quotes and string concatenations. The website i used to study used double quotes in html and single quotes in java. Didnt even realise. Glad i finally got it... – Michael Oct 28 '18 at 14:59
1

Using " instead of ' when:

<input value="user"/> //Standard html
<input value="user's choice"/> //Need to use single quote
<input onclick="alert('hi')"/> //When giving string as parameter for javascript function

Using ' instead of " when:

<input value='"User"'/> //Need to use double quote
var html = "<input name='username'/>" //When assigning html content to a javascript variable
a1204773
  • 6,923
  • 20
  • 64
  • 94
  • 3
    In your case of "assigning html content do js variable", i usually prefer to do the opposite: `var html = '';` and keep consistency with ther rest of html :) – Erenor Paz Mar 23 '14 at 17:32
1

if you are writing asp.net then occasionally you have to use double quotes in Eval statements and single quotes for delimiting the values - this is mainly so that the C# inline code knows its using a string in the eval container rather than a character. Personally I'd only use one or the other as a standard and not mix them, it looks messy thats all.

Mauro
  • 4,531
  • 3
  • 30
  • 56
0

I'm newbie here but I use single quote mark only when I use double quote mark inside the first one. If I'm not clear I show You example:

<p align="center" title='One quote mark at the beginning so now I can
"cite".'> ... </p>

I hope I helped.

Marcin C
  • 11
  • 1
0

Lots of great insightful replies here! More than enough for anyone to make a clear and personal decision.

I would simply like to point out one thing that's always mattered to me.
And take this with a grain of salt!

Double quotes apply to strings that have more than a single phase such as "one two" rather than single quotes for 'one' or 'two'. This can be traced as far back as C and C++.
(reference here or do your own online search).

And that's truly the difference.

With this principle (this different), parsing became possible such as "{{'a','b'},{'x','y'}} or "/[^\r\n]*[\r\n]" (which needed to be space independent because it's expressional) or more famously for HTML specific title = "Hello HTML!" or style = "font-family:arial; color:#FF0000;"

The funny thing here is that HTML (coming from XML itself) commonly adopted double quotes due to expressional features even if it is a single character (e.g. number) or single phase string.

As NibblyPig pointed out quite well and straightforward:
" as a top-tier and ' as a second tier since "'a string here'" is valid and expected by W3 standards (which is for the web) and will most likely never change.

And for consistency, double quotes is wisely used, but only fully correct by preference.

tfont
  • 10,891
  • 7
  • 56
  • 52
-5

In PHP using double quotes causes a slight decrease in performance because variable names are evaluated, so in practice, I always use single quotes when writing code:

echo "This will print you the value of $this_variable!";
echo 'This will literally say $this_variable with no evaluation.';

So you can write this instead;

echo 'This will show ' . $this_variable . '!';

I believe Javascript functions similarly, so a very tiny improvement in performance, if that matters to you.


Additionally, if you look all the way down to HTML spec 2.0, all the tags listed here;

W3 HTML DTD Reference

(Use doublequotes.) Consistency is important no matter which you tend to use more often.

Brombomb
  • 6,988
  • 4
  • 38
  • 57
Raiden
  • 484
  • 2
  • 8
  • 13
    JavaScript does not evaluate variable names in strings. There is no difference between ' and " in JavaScript. – John Mellor Aug 14 '12 at 12:08
-10

Double quotes are used for strings (i.e., "this is a string") and single quotes are used for a character (i.e., 'a', 'b' or 'c'). Depending on the programming language and context, you can get away with using double quotes for a character but not single quotes for a string.

HTML doesn't care about which one you use. However, if you're writing HTML inside a PHP script, you should stick with double quotes as you will need to escape them (i.e., \"whatever\") to avoid confusing yourself and PHP.

C.D. Reimer
  • 115
  • 11
  • 1
    I know quite a few programming languages, but one where this is true. – mikl Jul 03 '14 at 13:17
  • 2
    @mikl general practice in C# and Java is Strings in double quotes and chars in single quotes. But that gives no validation for this answer. Unless this is the answer to a different question. – Evorlor Jan 29 '15 at 14:22