DEV Community

Discussion on: Stop using so many divs! An intro to semantic HTML

programmerabhi profile image

Which tag should I use to display the code?

Thread Thread
kenbellows profile image
Ken Bellows Author • Edited on

For semantics purposes, use the <code> tag. For display purposes, to make it looks like code, it depends:

  • If it's an inline code snippet in the middle of a sentence, you can just use the <code> tag:
    The <code>while(condition)</code> loop is useful for loops with an unknown number of iterations

  • If it's an independent block of code, possibly with multiple lines, and you don't need syntax highlighting, you can wrap your <code> tag in the "preformatted text" tag, <pre>:

Below is an example of a while loop used to walk a graph of nodes:
const queue = [rootNode]
const prev = new Map()
const visited = new Set()
while (queue.length > 0)  {
  const node = queue.shift()
  for (const child of node.children) {
    if (visited.has(child)) {
    prev.set(child, node)
  • If you are worried about syntax highlighting, you should still wrap the whole thing in a <code> tag, but you're probably going to want to bring in a library that does the very hard work of parsing and highlighting your code, like Prism or highlight.js.

Bottom line, though, no matter what extra stuff you're doing for display purposes, code should always be wrapped in a <code> tag.