StartFoundationsComponentsContent

Code block

A code block shows source code for reading, with syntax colors, a copy button, and optional line numbers.

Stable Figma
OverviewUsageAPIAccessibility
interface User {
  id: number;
  name: string;
}
<tk-code-block language="ts"><pre>
interface User {
  id: number;
  name: string;
}
</pre></tk-code-block>

Anatomy

Part What it is
tk-code-block the element
default slot the code, ideally inside a <pre>
block part the bordered panel
header part the row with the language name and the copy button
scroll part the area that scrolls sideways

Put the code inside a <pre>. Until the script loads, the browser shows that <pre> as is, so the code stays readable. The component removes the shared indentation, so you can indent the code with your HTML.

Languages

npm install thykes
{ "theme": "dark", "primary": "blue" }
<tk-code-block language="bash"><pre>npm install thykes</pre></tk-code-block>
<tk-code-block language="json"><pre>{ "theme": "dark", "primary": "blue" }</pre></tk-code-block>

Set language to get colors and the language name in the header. Without it, or with an unknown value, the code shows as plain monospaced text. The language is never guessed.

language Also accepts
javascript js
typescript ts
jsx, tsx
html markup, xml, svg
css
json
bash shell, sh
python py
yaml yml

Line numbers

const total = items.reduce((sum, item) => sum + item.price, 0);
console.log(total);
<tk-code-block language="js" line-numbers><pre>
const total = items.reduce((sum, item) => sum + item.price, 0);
console.log(total);
</pre></tk-code-block>

line-numbers adds a column of numbers on the left. It stays in place when the code scrolls sideways. Screen readers skip it, and it's never selected or copied.

Copy and scrolling

  • The copy button copies the code without line numbers. The icon turns into a check, and screen readers hear "Copied to clipboard" (or "Copy failed"). Both reset after about 2 seconds.
  • Long lines don't wrap; the code scrolls sideways. When it overflows, the scroll area becomes a named region you can reach with Tab and scroll with the arrow keys. When the code fits, there's no extra tab stop.