DIsplay block of codes on a web page

Viewed 25

I am currently building a website containing code snippets and wondered how StackOverflow does it. I try to recreate it many times, but no matter what I do, I just can't recreate it and I can't find anyone or anything that explains how to do it. Does anyone know how StackOverflow manages to create code snippets like this:

#include <iostream>

int main(){
    std::cout << "Hello World!" << std::endl;
    return 0;
}

I know that it uses <pre> and <code> but even knowing that I can't find an explanation of what I need to do to recreate it. Can someone help me to find a way to recreate this code snippet style please?

1 Answers

(This answer assumes you want language-specific styling, not just monospace text)

Short answer: use a html code blocks library. This problem has been solved before!

I've heard highlight.js mentioned in passing before for this purpose, but there are a whole host of tools out there, some might be better-suited to your purpose.


Slightly longer answer:

Internally, any tool that generates styled HTML from source code is going to be parsing/tokenizing that source code using some language-specific ruleset. It essentially has some subset of the language's syntax rules, which can be used to interpret the raw text. This parsed/tokenized form is then used to build HTML/CSS based on that.

Related