Dark mode code block with prefixed line numbers Light mode code block with prefixed line numbers


I've always wanted to have line numbers prefixed in code blocks on questions / answers.
This userscript takes the code-blocks on the page, and inserts line numbers.

It will look at the length of the code block to determine the required additional padding, so a short code-block wouldn't have too much whitespace to allow for 3-digit line numbers.


Download Link

If you don't have a userscript client, you'll need one. TamperMonkey for Chrome or GreaseMonkey for FireFox are good options.


The best way is to leave a Github Issue for feature reqs, issues, and anything related to the userscript.


The code is on Github

  • You won't need to manually calculate the width of the line numbers element if you are using display: flex Commented Jul 14, 2023 at 15:07

3 Answers 3


Doesn't work on pages without any code highlighting because it waits for .hljs, and the code block does not have the class .s-code-block.

waitForKeyElements('.hljs', addLineNumbers, false);

Example question/page: https://stackoverflow.com/q/76688458

  • Good point! The next version looks for pre elements, which also means the line numbers don't need to wait for hljs to run :D Fixed in 1.2.
    – Cerbrus
    Commented Jul 14, 2023 at 17:06


The regex counting the number of lines should target the code element inside the pre element, and not the pre (parent) element itself.


The line numbers are selectable from the page. Suggested to make them unselectable by adding user-select: none; on top of pointer-events: none;


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .