Skip to content

Instantly share code, notes, and snippets.

@uditalias
Created September 21, 2020 20:32
Show Gist options
  • Save uditalias/3969a20ef759bf3a8757499429b30063 to your computer and use it in GitHub Desktop.
Save uditalias/3969a20ef759bf3a8757499429b30063 to your computer and use it in GitHub Desktop.
Adding line numbers to Docusaurus 2 CodeBlocks using only CSS
/* Edit the `src/css/custom.css` file and add the following styles */
/*
* Reset the line-number counter for each .prism-code scope
*/
.prism-code {
counter-reset: line-number;
}
/*
* Notice the chained .language-ts class name to .prism-code
* You can chain more languages in order to add line numbers
*/
.prism-code.language-ts .token-line::before {
counter-increment: line-number;
content: counter(line-number);
margin-right: calc(var(--ifm-pre-padding) * 1.5);
text-align: right;
min-width: 2.5rem;
display: inline-block;
opacity: .3;
position: sticky;
left: var(--ifm-pre-padding);
}
@uditalias
Copy link
Author

Adding line numbers to more languages by editing line 14

.prism-code.language-ts .token-line::before,
.prism-code.language-bash .token-line::before {
  ...
}

Support all languages:

.prism-code[class*=language-] .token-line::before {
  ...
}

@jsamr
Copy link

jsamr commented Apr 30, 2021

A variant with display: list-item:

@counter-style codeblock-line {
  system: extends decimal;
  suffix: ""
}

.prism-code {
  list-style: codeblock-line;
}

.prism-code .token-line::marker {
  color: var(--ifm-color-gray-700);
}

.prism-code .token-line {
  display: list-item;
  padding-left: var(--ifm-pre-padding);
  margin-left: var(--ifm-global-spacing);
}

@gtnardy
Copy link

gtnardy commented Aug 27, 2021

Another even shorter variant:

.prism-code {
  counter-reset: line-number;
}

.prism-code .token-line::marker {
  color: var(--ifm-color-gray-700);
  content: counter(line-number);
}

.prism-code .token-line {
  counter-increment: line-number;
  display: list-item;
  padding-left: var(--ifm-pre-padding);
  margin-left: var(--ifm-global-spacing);
}

@shyamzzp
Copy link

https://docusaurus.io/docs/markdown-features/code-blocks#line-numbering
I think you can add this property to the code-block to be able to see line numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment