CodeBlock Web Component

A lightweight, framework-agnostic web component for displaying code with syntax highlighting, line numbers, and more.

Get Started View on GitHub

Syntax Highlighting

CSS Custom Highlight API with Prism.js tokenization for 200+ languages.

Line Numbers

Optional line number gutter that stays in sync with content.

Copy Button

One-click code copying with visual feedback and custom events.

Code Folding

Collapse and expand code blocks for C-style languages.

Editable Mode

Make code blocks editable with live syntax highlighting.

Lightweight

~15kb minified, ~5.8kb gzipped. Zero runtime dependencies.

Installation

npm install codeblock-web-component
<link rel="stylesheet" href="https://unpkg.com/codeblock-web-component/dist/themes/themes.css"> <script type="module"> import { CodeBlock } from 'https://unpkg.com/codeblock-web-component/dist/codeblock.js'; await CodeBlock.define(); </script>

Usage

import { CodeBlock } from 'codeblock-web-component'; import 'codeblock-web-component/themes/themes.css'; // Register the custom element await CodeBlock.define();

Examples

Basic Syntax Highlighting

Just add a language attribute to enable syntax highlighting.

<code-block language="javascript">
function greet(name) { const message = `Hello, ${name}!`; console.log(message); return message; } // Call the function greet('World');

Line Numbers + Copy Button

Add line-numbers and copy-button attributes for additional features.

<code-block language="typescript" line-numbers copy-button>
interface User { id: number; name: string; email: string; } async function fetchUser(id: number): Promise<User> { const response = await fetch(`/api/users/${id}`); return response.json(); }

Code Folding

Enable with foldable attribute. Click the arrows to collapse/expand regions.

<code-block language="javascript" line-numbers foldable copy-button>
class Calculator { constructor(initialValue = 0) { this.value = initialValue; this.history = []; } add(n) { this.history.push({ op: 'add', value: n }); this.value += n; return this; } subtract(n) { this.history.push({ op: 'subtract', value: n }); this.value -= n; return this; } getHistory() { return this.history.map(entry => { return `${entry.op}: ${entry.value}`; }); } } const calc = new Calculator(10); calc.add(5).subtract(3); console.log(calc.value); // 12

Editable Mode

Add the editable attribute to make code editable. Try editing the CSS below!

<code-block language="css" editable copy-button>
.container { display: flex; flex-direction: column; gap: 1rem; padding: 2rem; background-color: #f5f5f5; border-radius: 8px; } .container:hover { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }

Multiple Languages

<code-block language="python" line-numbers>
def fibonacci(n): """Calculate the nth Fibonacci number.""" if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) # Print first 10 Fibonacci numbers for i in range(10): print(f"F({i}) = {fibonacci(i)}")
<code-block language="html" line-numbers>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello World</title> </head> <body> <h1>Hello, World!</h1> <p>Welcome to my website.</p> </body> </html>
<code-block language="rust" line-numbers>
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let doubled: Vec<i32> = numbers .iter() .map(|x| x * 2) .collect(); println!("{:?}", doubled); }

API Reference

Attributes

Attribute Type Description
language string Programming language for syntax highlighting
line-numbers boolean Show line number gutter
copy-button boolean Show copy-to-clipboard button
editable boolean Make content editable
foldable boolean Enable code folding

Events

Event Detail Description
copy { value, success } Fired when code is copied
change { value } Fired when content changes (editable mode)

Event Example

const codeBlock = document.querySelector('code-block'); codeBlock.addEventListener('copy', (e) => { console.log('Copied:', e.detail.value); console.log('Success:', e.detail.success); }); codeBlock.addEventListener('change', (e) => { console.log('New content:', e.detail.value); });

Theming

Switch between built-in themes using the data-theme attribute on any parent element:

<!-- Default: Prettylights theme --> <html> <code-block language="js">...</code-block> </html> <!-- Prism theme --> <html data-theme="prism"> <code-block language="js">...</code-block> </html>

Custom Theme

Create your own theme by overriding CSS custom properties:

[data-theme="my-theme"] { --cb-bg: #1e1e1e; --cb-fg: #d4d4d4; --cb-comment: #6a9955; --cb-constant: #4fc1ff; --cb-entity: #dcdcaa; --cb-entity-tag: #569cd6; --cb-keyword: #c586c0; --cb-string: #ce9178; --cb-variable: #9cdcfe; } [data-theme="my-theme"] code-block { font-family: 'Fira Code', monospace; font-size: 13px; }