Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make code blocks like those in markdown for html?

Markdown support code blocks that are very useful. By specifying which language we want (like this ```cpp), we can have color syntax highlighting automatically too. Example shown below.

#include <iostream>
int main(){
    printf("hello");
}

So, my question is how do I do this on an html file?

I already know you can make code blocks, with this -> <pre><code> write here </code></pre>, but I want the syntax highlighting function.

Any guidance would be appreciated. Thanks.

like image 556
Kevin Avatar asked Jan 23 '26 17:01

Kevin


1 Answers

You would want to use a library like highlight.js

Otherwise you would have to wrap every key word, variable, function name, operators, etc. in their own span tag and apply classes, creating a color schema for every distinct thing in every supported language.
Other than using a library (or creating your own, for fun) this is rather tedious.

FYI: Ever thought about right-click and inspect element of your example? Your example results in this HTML:

<pre class="lang-cpp s-code-block hljs"><code><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"hello"</span>);
}
</code></pre>

As you can see this would be pretty tedious to create yourself, so use a library for that.

like image 51
Peter Krebs Avatar answered Jan 25 '26 10:01

Peter Krebs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!