Skip to main content Home About the Design SystemRoadmap OverviewDesignersDevelopers OverviewColorGridIconographyInteractionsSpacingTypography Overview Global colorBox shadowTypographyBorderOpacitySpaceLengthIconBreakpointsMedia queries All elements Accordion Alert Announcement Audio player Avatar Back to top Badge Blockquote Breadcrumb Button Card Chip Code block Call to action Dialog Disclosure Footer Health index Icon Jump links Menu dropdown Navigation link Navigation (primary) Navigation (secondary) Navigation (vertical) Pagination PopoverPlanned Progress stepper Scheme toggle Site status Skeleton Skip link Spinner Statistic Subnavigation Surface Switch Table Tabs Tag Tile Timestamp Tooltip Video embed OverviewColor PalettesCustomizingDevelopers All PatternsAccordionAlertCall to ActionCardFilterFormLink with iconLogo wallSearch barSticky bannerSticky cardTabsTagTile All Personalization PatternsAnnouncement FundamentalsAccessibility toolsAssistive technologiesCI/CDContentContributorsDesignDevelopmentManual testingResourcesScreen readers Design/code status Release notes Get support

Code block

OverviewStyleGuidelinesCodeAccessibilityDemos
ImportingUsagerh-code-blockImportingUsagerh-code-block

Importing

Add rh-code-block to your page with this import statement:

<script type="module">
  import '@rhds/elements/rh-code-block/rh-code-block.js';
</script>
Copy to Clipboard Wrap lines

To learn more about installing RHDS elements on your site using an import map read our getting started docs.

Lightdom CSS

This element requires you to load "Lightdom CSS" stylesheets for styling deeply slotted elements.

Note

Replace /path/to/ with path to the CSS file, whether local or CDN.

<link rel="stylesheet" href="/path/to/rh-code-block/rh-code-block-lightdom.css">

Usage

<rh-code-block>
<script type="text/html"><!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
  function $init() {return true;}
<</script><script type="text/html">/script>
<body>
  <p checked class="title" id="title">Title</p>
  <!-- here goes the rest of the page -->
</body></script>
</rh-code-block>

<script type="module">
  import '@rhds/elements/rh-code-block/rh-code-block.js';
</script>
Copy to Clipboard Wrap lines

Code block content must be placed inside a non-executable <script> tag. The type attribute is what makes it non-executable, it must not be module, importmap, javascript, or any of the executable javascript mimetypes.

The type value only prevents the browser from running the content; it does not affect display or syntax highlighting. Using a MIME type that matches your content (e.g. text/html, text/css, text/yaml) is a useful convention for editor tooling but is not required by the component.

For JavaScript, use text/sample-javascript since text/javascript is executable.

<rh-code-block>
  <script type="text/sample-javascript">
  import '@rhds/elements/rh-code-block/rh-code-block.js';
  </script>
</rh-code-block>

Warning

When slotting HTML content into the code-block, if that HTML content contains a </script> end tag, you must escape it.

One approach to escaping script tags is to close the containing <script type="text/html"> within the sample's closing script tag, then immediately open a new sample script tag containing the rest of the snippet. Another method is to insert a zero-width-joiner (or some other unusual unicode character) in the closing script tag, and use javascript to remove it before copying the content to the clipboard. Each method has benefits and drawbacks.

<rh-code-block>
  <script type="text/html">
<p>Script tags in HTML must be escaped</p>
<script>console.log('Success!');<</script><script type="text/html">/script>
  </script>
</rh-code-block>

Syntax highlighting

To enable syntax coloring, set highlighting and language on the <rh-code-block> element:

Attribute Purpose Values
highlighting Enables the Prism.js engine client or prerendered
language Selects the Prism grammar used to colorize tokens html, css, javascript, typescript, bash, ruby, yaml, json

Each language value maps directly to a bundled Prism grammar module. If we are missing the grammar module you need, please create an issue on our Github repository with your request.

Without both attributes, the code block displays plain monospace text with no syntax coloring.

<rh-code-block highlighting="client"
               language="html">
  <script type="text/html">
<p>This content is highlighted as HTML by client side highlighting.</p>
  </script>
</rh-code-block>

Copy Button

Add the value copy to the actions attribute, and a helpful copy button will appear next to the code content. You may listen for the copy event and modify its content property to change the text copied to the clipboard. For example, to remove a shell prompt ($ ) from the copied text, use this listener function:

import {RhCodeBlockCopyEvent} from '@rhds/elements/rh-code-block/rh-code-block.js';

document.body.addEventListener('copy', function(event) {
  if (event instanceof RhCodeBlockCopyEvent) {
    // remove prompt and surrounding whitespace from the start of the string
    event.content = event.content.replace(/^\s*\$|#\s*/, '');
  }
});

rh-code-block

A read-only code viewer for formatted snippets that allows syntax highlighting, line numbers, and copy/wrap actions. Source must be in a <script type="text/sample-..."> or <pre> child. The code region is keyboard-scrollable; screen readers announce it via ARIA as a scrollable area. Authors should avoid nesting interactive elements inside the code slot.

Slots 6

Slot Name Summary Description
[default]

code content (default slot)

Expects a non-executable <script type="text/sample-..."> or <pre> element containing source code. JavaScript samples should use type="text/sample-javascript". This region is keyboard-scrollable and exposed to assistive technology as a scrollable code area; avoid placing focusable or interactive children here.
Note: [default] unnamed slots do not have a slot="name" attribute.

action-label-copy

copy button label (action-label-copy slot)

Expects inline text or <span> elements providing labels for the copy button's default, active, and failed states. Wired to aria-labelledby so screen readers announce the current state.

action-label-wrap

wrap button label (action-label-wrap slot)

Expects inline text or <span> elements providing labels for the wrap toggle's default and active states. Wired to aria-labelledby so screen readers announce the current state.

show-more

collapsed toggle label (show-more slot)

Expects inline text for the expand button when code is collapsed. Defaults to "Show more". Wired to aria-labelledby so screen readers announce it as the button's accessible name.

show-less

expanded toggle label (show-less slot)

Expects inline text for the collapse button when code is expanded. Defaults to "Show less". Wired to aria-labelledby so screen readers announce it as the button's accessible name.

legend

code callout legend (legend slot)

Expects a <dl> element containing <rh-badge> in <dt> and legend text in <dd> elements. Provides a key for callout annotations within the code block. Screen readers announce the list structure so users can correlate badges with their descriptions. Hidden when no content is slotted.

Attributes 9

Attribute DOM Property Description Type Default
actions actions

Space- or comma-separated list of action buttons to display. Accepts 'copy', 'wrap', or both (e.g. "copy wrap"). 'copy' adds a clipboard button; 'wrap' adds a word-wrap toggle. Defaults to [] (no actions shown). Labels can be overridden via the action-label-copy and action-label-wrap slots for internationalization. The active-state element must have hidden data-code-block-state="active".

<rh-code-block actions="copy wrap">
<span slot="action-label-copy">Copy to Clipboard</span>
<span slot="action-label-copy" hidden data-code-block-state="active">Copied!</span>
<span slot="action-label-copy" hidden data-code-block-state="failed">Copy failed!</span>
<span slot="action-label-wrap">Toggle word wrap</span>
<span slot="action-label-wrap" hidden data-code-block-state="active">Toggle overflow</span>
</rh-code-block>
('copy' | 'wrap')[]
[]
highlighting highlighting

Controls how syntax highlighting is applied. Accepts 'client' or 'prerendered'. When 'client', Prism.js is loaded on-demand and highlights source from <script> children. When 'prerendered', RHDS token colors are applied to existing Prism class names in child <pre> elements. Defaults to undefined (no highlighting).

'client' | 'prerendered'
unknown
language language

Specifies the Prism.js grammar for client-side highlighting. Requires highlighting="client". Accepts 'html' | 'css' | 'javascript' | 'typescript' | 'bash' | 'ruby' | 'yaml' | 'json'. Defaults to undefined. When omitted, no syntax coloring is applied.

'html' | 'css' | 'javascript' | 'typescript' | 'bash' | 'ruby' | 'yaml' | 'json'
unknown
compact compact

When true, reduces internal padding for tighter layouts. Defaults to false.

boolean
false
dedent dedent

When true, strips common leading whitespace from source lines before rendering. Defaults to false.

boolean
false
resizable resizable

When true, allows the user to vertically resize the code area by dragging. Defaults to false.

boolean
false
full-height fullHeight

When true, the code block expands to its full height without scroll truncation. Defaults to false.

boolean
false
wrap wrap

When true, long lines wrap instead of scrolling horizontally. Defaults to false.

boolean
false
line-numbers lineNumbers

Controls line-number visibility. Accepts 'hidden' or 'visible'. When 'hidden', the gutter column is removed. Defaults to undefined (visible).

'hidden' | 'visible'
unknown

Methods 2

Method Name Description
fromAttribute()

Converts the HTML attribute string to an array of action names. Splits on spaces or commas, trims whitespace, and filters empty values.

toAttribute()

Converts the array of action names to an HTML attribute string. Joins array values with spaces.

Events 1

Event Name Description
copy

Fired when the user clicks the copy button or presses Enter/Space on it. The event.content property contains the text to copy (string). Cancel with preventDefault() to suppress clipboard write. Mutate event.content to alter copied text.

CSS Shadow Parts 0

None

CSS Custom Properties 2

CSS Property Description Default
--rh-code-block-callout-size var(--rh-size-icon-02, 24px)
--rh-code-block-border-block-start-width

Design Tokens 44

Token Description Copy
--rh-length-3xl

Action button width

Action button height

48px length token

Full CSS Variable Permalink to this token
--rh-color-surface

Action button hover background

Full CSS Variable Permalink to this token
--rh-size-icon-02

Action icon width

Action icon height

24px icon box

Full CSS Variable Permalink to this token
--rh-color-surface-lighter

Code surface in light mode

Tertiary surface (light theme)

Full CSS Variable Permalink to this token
--rh-color-surface-dark

Tertiary surface (dark theme)

Full CSS Variable Permalink to this token
--rh-space-xl

Container main spacer

24px spacer

Full CSS Variable Permalink to this token
--rh-color-blue-10

Selected text background in light mode

Alert - Info background

Full CSS Variable Permalink to this token
--rh-color-gray-40

Punctuation token color in light mode

Subtle icon (hover state)

Full CSS Variable Permalink to this token
--rh-color-gray-20

Default syntax token color in dark mode

Punctuation token color in dark mode

Secondary surface (light theme)

Full CSS Variable Permalink to this token
--rh-color-gray-95

Default syntax token color in light mode

Selected text background in dark mode

Namespace token color in light mode

Primary surface (dark theme) or primary text (light theme)

Full CSS Variable Permalink to this token
--rh-color-red-10

Tag token color in dark mode

Full CSS Variable Permalink to this token
--rh-color-purple-50

Property token color in light mode

Tag token color in light mode

Boolean token color in light mode

Number token color in light mode

Constant token color in light mode

Symbol token color in light mode

Deleted token color in light mode

Function name token color in light mode

Full CSS Variable Permalink to this token
--rh-color-teal-20

Function name token color in dark mode

Full CSS Variable Permalink to this token
--rh-color-red-40

Namespace token color in dark mode

Deleted token color in dark mode

Attribute name token color in dark mode

Light brand red

Full CSS Variable Permalink to this token
--rh-color-teal-60

Selector token color in light mode

Attribute name token color in light mode

String token color in light mode

Character token color in light mode

Built-in token color in light mode

Inserted token color in light mode

Full CSS Variable Permalink to this token
--rh-color-yellow-60

Operator token color in light mode

Entity token color in light mode

URL token color in light mode

Full CSS Variable Permalink to this token
--rh-color-blue-40

Operator token color in dark mode

Entity token color in dark mode

URL token color in dark mode

Alert - Info accent

Full CSS Variable Permalink to this token
--rh-color-blue-60

At-rule token color in light mode

Attribute value token color in light mode

Keyword token color in light mode

Inline link hover (light theme)

Full CSS Variable Permalink to this token
--rh-color-orange-40

Boolean token color in dark mode

Number token color in dark mode

Function token color in dark mode

Label - Filled (Orange) accent color

Full CSS Variable Permalink to this token
--rh-color-red-60

Function token color in light mode

Class name token color in light mode

Dark brand red

Full CSS Variable Permalink to this token
--rh-color-yellow-40

Property token color in dark mode

Constant token color in dark mode

Symbol token color in dark mode

Class name token color in dark mode

Alert - Warning accent

Full CSS Variable Permalink to this token
--rh-color-purple-30

Selector token color in dark mode

Built-in token color in dark mode

At-rule token color in dark mode

Keyword token color in dark mode

Important token color in dark mode

Full CSS Variable Permalink to this token
--rh-color-orange-60

Regex token color in light mode

Important token color in light mode

Variable token color in light mode

Full CSS Variable Permalink to this token
--rh-color-green-40

String token color in dark mode

Character token color in dark mode

Inserted token color in dark mode

Attribute value token color in dark mode

Regex token color in dark mode

Variable token color in dark mode

Full CSS Variable Permalink to this token
--rh-border-radius-default

Action button corner radius

Container corner radius

3px border radius; Example: Card

Full CSS Variable Permalink to this token
--rh-size-icon-06

Callout tag width

64px icon box

Full CSS Variable Permalink to this token
--rh-font-family-code

Code content typeface

Prerendered code typeface

Line number typeface

Code font family

Full CSS Variable Permalink to this token
--rh-color-text-secondary

CDATA syntax token color

Comment syntax token color

Block comment syntax token color

Doctype syntax token color

Line number text color

Full CSS Variable Permalink to this token
--rh-font-weight-code-regular

Line number font weight

Regular font weight

Full CSS Variable Permalink to this token
--rh-border-width-sm

Container border width

Top border width fallback

Line number gutter border width

1px border width; Example: Secondary CTA or Button

Full CSS Variable Permalink to this token
--rh-color-border-subtle

Container border color

Line number gutter border color

Full CSS Variable Permalink to this token
--rh-line-height-code

Prerendered code line height

Sizer line height

Line number item height

Line height for code

Full CSS Variable Permalink to this token
--rh-color-text-primary

Action icon color

Container text color

Expand button text color

Full CSS Variable Permalink to this token
--rh-font-family-body-text

Expand button typeface

Body text font family

Full CSS Variable Permalink to this token
--rh-font-size-body-text-sm

Expand button text size

14px font size

Full CSS Variable Permalink to this token
--rh-font-weight-body-text-regular

Expand button font weight

Regular font weight

Full CSS Variable Permalink to this token
--rh-line-height-body-text

Expand button line height

Line height for body text

Full CSS Variable Permalink to this token
--rh-color-icon-secondary

Expand icon color

Full CSS Variable Permalink to this token
--rh-space-sm

Compact secondary spacer

6px spacer

Full CSS Variable Permalink to this token
--rh-font-size-code-md

16px font size

Full CSS Variable Permalink to this token
--rh-space-3xl

Truncation gradient height

48px spacer

Full CSS Variable Permalink to this token
--rh-space-4xl

Overflow gradient width

64px spacer

Full CSS Variable Permalink to this token
--rh-space-lg

Content lines column gap

Actions toolbar block start margin

Actions toolbar inline end margin

Compact main spacer

Legend block margin

16px spacer

Full CSS Variable Permalink to this token
--rh-space-md

Action button padding

Line number inline padding

Actions toolbar gap

Expand button secondary spacer

Expand button gap

Legend grid gap

8px spacer

Full CSS Variable Permalink to this token
© 2026 Red Hat Deploys by Netlify