Why Use <code> When There's <pre>?
The <pre> tag defines pre-formatted text. Text used within this tag has a fixed width, IOW it uses a mono-spaced font, usually courier.
It looks like this.
The <code> tag works similarly, though it's written specifically for code. It looks like this
. Occasionally I post some code on the blog, and every time I wonder... which tag should I use to include it? I usually settle for code... since that's what I'm posting. Reading the basics anew I started wondering, why use code when there's pre? What's the difference? Why did W3C add an extra tag with the same properties and manner of display?
It turns out there is a difference! The <code> tag is meant to be used for inline code that can wrap and the <pre> tag for block code that must not wrap (see example above). Additionally, you could wrap the <pre> tag around a <code> tag to turn the inline code into a block (but never vice-versa). This might be extra useful if you've styled the code element through CSS or JS to display it in numbered rows, or a different color, or something fancy that makes it look like kind of like you're looking at the source code when you're seeing a page, but you don't want to make all code appear as a block. The <pre> tag can be used for many things other than code, too.
when I first included a line of code, I thought the <code> tag would take care of everything. That it would not only keep all tabs and spaces intact but also display all the tags in text form. Turns out this was not the case. When including code on a page, either the left or right bracket in a tag (or even better, both) must be replaced with < or/and > to remain in their regular text form.
Btw, if you want to show the code for the < and > brackets (< and >), you'll need to escape the & at the start of the code by using &, like I did above. Just recently I wrote &amp; so you could see the &, but of course I had to add an & so you could see both of them, which means I actually had three amps in a row. What you see is never really how it looks! Including code is complicated! :D