Utilizing a code block in Markdown format results in its conversion to HTML code, encapsulated within <pre><code>
markup. By default, there is no line numbering; it’s a straightforward code block display. To incorporate line numbering and apply some CSS styling through SCSS, I employed vanilla JavaScript code:
(function() {
var pre = document.getElementsByTagName('pre'),
pl = pre.length;
for (var i = 0; i < pl; i++) {
pre[i].innerHTML = '<span class="line-number"></span>' + pre[i].innerHTML + '<span class="cl"></span>';
var num = pre[i].innerHTML.split(/\n/).length;
for (var j = 0; j < (num - 1); j++) {
var line_num = pre[i].getElementsByTagName('span')[0];
line_num.innerHTML += '<span>' + (j + 1) + '</span>';
}
}
})();
My SCSS code:
code,
pre {
font-family: $font-precode;
font-variant-ligatures: none;
font-feature-settings: "liga" 0;
}
code {
background: var(--code-bg);
color: var(--code-color);
}
pre {
width: 100%;
margin: 0 0 1rem 0;
line-height: 1.4;
white-space: pre;
overflow: auto;
padding: 0.5rem 2rem 0.5rem 0.5rem;
font-size: 0.9rem;
code {
padding: 0;
}
.line-number {
float: left;
margin: 0 1em 0 -1em;
user-select: none; /* Standard */
text-align: right;
span {
display: block;
padding: 0 0.5em 0 1em;
}
}
.cl {
display: block;
clear: both;
}
}