탐색

v2.1.0
타이포그래피

코드

텍스트를 입력된 그대로 고정폭 글꼴로 표시합니다. 인라인이나 블록으로 사용할 수 있습니다.

이 페이지의 내용

코드는 명령어, 값, 파일 이름처럼 적힌 그대로 보여 주는 고정폭 글꼴의 텍스트입니다. 인라인에서는 <code>에 .code를 적용하면 텍스트 줄 안에 작은 칩으로 표시됩니다. 블록에서는 <pre>에 code-block을 적용하면 줄이 길 때 블록 자체를 가로로 스크롤할 수 있는 오목한 영역이 됩니다.

코드

<p class="m(0) text-sm fg-text-body leading-md">  Install the package with <code class="code">npm install @master/ui</code>, then import it after <code class="code">@master/css</code>.</p>
<p className="m(0) text-sm fg-text-body leading-md">  Install the package with <code className="code">npm install @master/ui</code>, then import it after <code className="code">@master/css</code>.</p>
<p class="m(0) text-sm fg-text-body leading-md">  Install the package with <code class="code">npm install @master/ui</code>, then import it after <code class="code">@master/css</code>.</p>
<template>  <p class="m(0) text-sm fg-text-body leading-md">    Install the package with <code class="code">npm install @master/ui</code>, then import it after <code class="code">@master/css</code>.  </p></template>

#블록

<pre>에 code-block을 적용하고, 코드의 의미를 전달할 수 있도록 그 안에 <code>를 둡니다. 기존 줄바꿈은 유지되며, 긴 줄은 자동으로 줄바꿈되지 않고 블록을 가로로 스크롤할 수 있습니다. 줄이 블록 너비를 넘을 수 있다면 키보드로 스크롤할 수 있도록 tabindex="0"을 지정합니다.

블록

<pre class="code-block" tabindex="0"><code>@import '@master/css';@import '@master/ui';@theme {--color-brand: var(--color-indigo-50);}</code></pre>
<pre class="code-block" tabindex="0"><code>@import '@master/css';@import '@master/ui';@theme {'{'}--color-brand: var(--color-indigo-50);{'}'}</code></pre>
<template>  <pre class="code-block" tabindex="0"><code>@import '@master/css';@import '@master/ui';@theme {--color-brand: var(--color-indigo-50);}</code></pre></template>

#코드 줄

특정 줄을 따로 표시하려면 각 줄을 요소로 감싸고 각 요소에 code-line을 적용합니다. 그러면 블록이 줄을 그리드로 배치합니다. 모든 줄의 너비가 가장 긴 줄에 맞춰지므로 특정 줄에 적용한 강조 띠가 스크롤 영역 전체 너비를 채웁니다. 그리드 항목 사이의 공백은 렌더링되지 않으므로 요소 사이에서 줄을 바꿔도 빈 줄이 생기지 않습니다. 코드 한 줄마다 요소 하나를 사용합니다.

code-line-highlight는 강조할 줄에 옅은 배경색을 입히고 줄 시작 부분에 진한 선을 표시합니다. 블록에 code-numbered를 적용하면 CSS 카운터로 줄 번호를 매깁니다. 줄 번호는 코드 옆 여백에 표시되며 코드와 함께 선택되거나 복사되지 않습니다.

줄 번호와 줄 강조

<pre class="code-block code-numbered" tabindex="0"><code class="code-line">.btn {</code><code class="code-line">  --btn-height: 2.375rem;</code><code class="code-line code-line-highlight">  --btn-radius: var(--radius-control);</code><code class="code-line">  border-radius: calc(var(--btn-radius) * var(--corner-scale));</code><code class="code-line">  corner-shape: var(--corner-shape);</code><code class="code-line">}</code></pre>
<pre class="code-block code-numbered" tabindex="0"><code class="code-line">.btn {'{'}</code><code class="code-line">  --btn-height: 2.375rem;</code><code class="code-line code-line-highlight">  --btn-radius: var(--radius-control);</code><code class="code-line">  border-radius: calc(var(--btn-radius) * var(--corner-scale));</code><code class="code-line">  corner-shape: var(--corner-shape);</code><code class="code-line">{'}'}</code></pre>
<template>  <pre class="code-block code-numbered" tabindex="0"><code class="code-line">.btn {</code><code class="code-line">  --btn-height: 2.375rem;</code><code class="code-line code-line-highlight">  --btn-radius: var(--radius-control);</code><code class="code-line">  border-radius: calc(var(--btn-radius) * var(--corner-scale));</code><code class="code-line">  corner-shape: var(--corner-shape);</code><code class="code-line">}</code></pre></template>

#코드 변경 비교

변경된 줄은 code-line-added와 code-line-removed로 표시합니다. 각 줄의 색상은 줄 첫머리의 기호와 대응합니다. 패치에서처럼 텍스트에 +와 -를 그대로 두면 색상 없이도 변경 내용을 구분할 수 있고, 복사한 결과를 패치로 사용할 수 있습니다.

코드 변경 비교

<pre class="code-block" tabindex="0"><code class="code-line">  @theme {</code><code class="code-line code-line-removed">-   --radius-control: .5rem;</code><code class="code-line code-line-added">+   --radius-control: .625rem;</code><code class="code-line">    --radius-surface: 1rem;</code><code class="code-line">  }</code></pre>
<pre class="code-block" tabindex="0"><code class="code-line">  @theme {'{'}</code><code class="code-line code-line-removed">-   --radius-control: .5rem;</code><code class="code-line code-line-added">+   --radius-control: .625rem;</code><code class="code-line">    --radius-surface: 1rem;</code><code class="code-line">  {'}'}</code></pre>
<template>  <pre class="code-block" tabindex="0"><code class="code-line">  @theme {</code><code class="code-line code-line-removed">-   --radius-control: .5rem;</code><code class="code-line code-line-added">+   --radius-control: .625rem;</code><code class="code-line">    --radius-surface: 1rem;</code><code class="code-line">  }</code></pre></template>

#패널

code-panel은 블록 위에 헤더를 배치해 하나의 오목한 영역으로 묶습니다. 헤더에는 code-title로 표시한 파일 이름과 끝에 놓인 컨트롤이 들어갑니다. 컨트롤은 가장자리에서 4px 안쪽에 놓이며 바깥 모서리와 중심이 같은 둥근 모서리를 사용합니다. 내부 블록에는 별도의 오목한 영역이 표시되지 않습니다.

독립된 code-block 또는 이를 감싸는 code-panel에 --code-radius를 설정합니다. 기본값은 var(--radius-control)입니다. 트레이의 직계 자식인 루트에는 var(--radius-surface)가 적용되어, 트레이 안쪽으로 들어간 간격에 맞춰 모서리가 둥글게 처리됩니다. 패널 안의 블록은 모서리가 직각이고 배경이 투명해 전체에 하나의 윤곽선만 보입니다.

복사에는 스크립트가 필요합니다. 블록의 텍스트를 읽어 클립보드에 쓰는 데는 세 줄이면 충분합니다.

패널

<div class="code-panel">  <div class="code-header">    <span class="code-title">app.css</span>    <button type="button" class="btn btn-quiet btn-sm" id="copy-app-css">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <path d="M3 1.5H9A1.4999 1.4999 0 0 1 10.5 3V4.25H9.5V3A0.5002 0.5002 0 0 0 9 2.5H3A0.5002 0.5002 0 0 0 2.5 3V9A0.5002 0.5002 0 0 0 3 9.5H4.25V10.5H3A1.4999 1.4999 0 0 1 1.5 9V3A1.4999 1.4999 0 0 1 3 1.5Z" fill="currentColor" stroke="none" fill-rule="evenodd" /><rect x="5.5" y="5.5" width="8.5" height="8.5" rx="1" />      </svg>Copy    </button>  </div>  <pre class="code-block" tabindex="0"><code>@import '@master/css';@import '@master/ui';@theme {--color-brand: var(--color-indigo-50);}</code></pre>  <output class="sr-only"></output></div><script>document.getElementById('copy-app-css').addEventListener('click', function (event) {var button = event.currentTargetvar status = button.closest('.code-panel').querySelector('output')navigator.clipboard.writeText(button.closest('.code-panel').querySelector('.code-block').textContent).then(function () {  button.lastChild.textContent = 'Copied'  status.textContent = 'Copied'  setTimeout(function () {    button.lastChild.textContent = 'Copy'    status.textContent = ''  }, 1600)})})</script>

#코드와 kbd

독자가 텍스트로 입력하거나 프로그램에서 읽는 내용에는 code를 사용하고, 눌러야 할 키에는 kbd를 사용합니다. 스타일시트는 구문 강조를 적용하지 않습니다. 구문 강조 도구가 만든 span 요소는 블록 안에서도 각자의 색상을 유지합니다.

#클래스

클래스설명
code<code> 요소에 적용하는 인라인 코드 스타일입니다. 텍스트 줄 안에 작은 칩으로 표시됩니다
code-block<pre> 요소에 적용하는 코드 블록 스타일입니다. 줄바꿈을 유지하며 가로로 스크롤할 수 있는 오목한 영역으로 표시됩니다. 블록 너비를 넘는 줄이 있을 수 있다면 tabindex="0"을 지정하세요.
code-line블록의 한 줄을 <code> 또는 <span> 요소로 표시합니다. 각 줄을 마크업으로 지정하면 블록은 줄을 그리드로 배치하고 모든 줄의 너비를 가장 긴 줄에 맞춥니다.
code-line-highlight설명하는 줄에 옅은 배경색을 적용하고 줄 시작 쪽에 잉크 색상의 2px 선을 표시합니다.적용할 클래스는 code-line입니다
code-line-addeddiff에서 추가된 줄은 성공 색상으로 표시합니다. 텍스트에 + 기호를 유지하세요.적용할 클래스는 code-line입니다
code-line-removeddiff에서 삭제된 줄을 위험 상태를 나타내는 색으로 표시합니다. 텍스트의 - 기호를 유지하세요.적용할 클래스는 code-line입니다
code-numberedCSS 카운터로 블록의 code-line 요소에 줄 번호를 매깁니다. 줄 번호는 선택하거나 복사할 수 없는 여백에 표시됩니다.적용할 클래스는 code-block입니다
code-panel헤더와 블록을 하나의 오목한 영역으로 감쌉니다. 안쪽 블록에는 별도의 오목한 영역이 표시되지 않습니다
code-header블록 위에 놓이는 40px 높이의 바로, 시작 쪽에 이름을, 끝 쪽에 컨트롤을 배치합니다. 복사 버튼을 두려면 블록의 텍스트를 클립보드에 복사하는 스크립트가 필요합니다.
code-title헤더에 표시하는 파일 이름 또는 언어 이름

#사용자 지정 속성

속성기본값설명
--code-radiusvar(--radius-control)모서리 배율을 적용하기 전 독립 코드 블록의 원형 모서리 반경code-block에 설정합니다
--code-radiusvar(--radius-control)모서리 배율을 적용하기 전 패널의 원형 모서리 반경입니다. 패널 안쪽의 컨트롤에도 이 값을 사용합니다. 패널이 트레이에 바로 담기는 경우에는 var(--radius-surface)를 사용하세요.code-panel에 설정합니다
--code-gutter2ch줄 번호가 들어가는 여백의 너비입니다. 기본값은 두 자리이며, 100줄 이상인 목록에서는 3ch로 설정해야 번호가 정렬됩니다.code-numbered에 설정합니다

#접근성

  • 줄이 블록 너비를 넘을 수 있다면 키보드로 스크롤할 수 있도록 블록에 tabindex="0"을 지정합니다.
  • 줄 번호는 생성된 콘텐츠입니다. 스크린 리더가 읽지 않으며 선택하거나 복사할 수 없습니다.
  • 줄 강조는 시각적 표시입니다. 블록 주변의 설명에서 특정 줄을 가리킬 때는 색상이나 줄 번호 대신 그 줄의 내용을 직접 언급합니다.

#소스

@master/ui/components/code.css
/* * Code: literal text in the mono face. Inline, it is a small chip in the line; as a block, a well that * scrolls on its own when a line is long. * A block may mark its lines. Each line is then a code-line, and the block lays them out as a grid, so a * line's band runs the whole scrolling width and the line breaks between the spans cost nothing. Lines can * be numbered by a CSS counter, highlighted, or marked as added and removed in a diff. * A panel puts a header over the block: the file's name and a control, in one well. * Code is literal: the spacing a page may add between Han and Latin letters (text-autospace), the trimming of * CJK punctuation (text-spacing-trim) and a hyphen at a line break would paint a form that is not the source, * so the inline chip, the block and the title turn all three off. */@layer components.ui {  .code {    padding: .125em .375em;    border-radius: calc((var(--radius-chip) - 2px) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--code-tone, var(--color-surface-chip));    color: var(--code-ink, var(--color-text-strong));    box-shadow: inset 0 0 0 .5px var(--code-line, var(--color-line-contour));    font: 400 .875em/1.4 var(--font-family-mono);    font-variant-ligatures: none;    text-autospace: no-autospace;    text-spacing-trim: space-all;    hyphens: none;    overflow-wrap: anywhere;    /* Set in a right-to-left sentence, a run of code keeps the order it was written in, signs and slashes included. */    unicode-bidi: plaintext;    /* Broken across lines, each piece keeps the chip's padding, corner and edge. */    -webkit-box-decoration-break: clone;    box-decoration-break: clone;    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /* On a <pre>. Lines keep their breaks and the block scrolls sideways. */  .code-block {    --code-radius: var(--radius-control);    --code-padding-x: 1rem;    --code-padding-y: .875rem;    margin: 0;    padding: var(--code-padding-y) var(--code-padding-x);    border-radius: calc(var(--code-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: auto;    background: var(--color-surface-inset);    color: var(--color-text-strong);    box-shadow: var(--shadow-pressed);    font: 400 .8125rem/1.65 var(--font-family-mono);    font-variant-ligatures: none;    text-autospace: no-autospace;    text-spacing-trim: space-all;    tab-size: 2;    white-space: pre;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;    overscroll-behavior-inline: contain;    &:focus-visible {      @apply --focus-ring;    }    /*     * Marked lines: the block becomes a grid of lines, each as wide as the longest. White space between the     * line elements is not rendered in a grid, so the markup may keep one line of source per line of code.     */    &:has(.code-line) {      display: grid;      align-content: start;      counter-reset: code-line;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /* One line of a block. It bleeds to the block's edges, so a band on it meets the well's contour. */  .code-line {    display: block;    min-height: 1lh;    /* The 2px rule a marked line draws at its start: on the left, or on the right of a right-to-left line. */    --code-line-rule: 2px;    margin-inline: calc(-1 * var(--code-padding-x));    padding-inline: var(--code-padding-x);    counter-increment: code-line;    &:dir(rtl) {      --code-line-rule: -2px;    }    /* The line being talked about: a tint, and a 2px rule of ink at its start. */    &.code-line-highlight {      background: color-mix(in oklab, var(--color-text-strong) 6%, transparent);      box-shadow: inset var(--code-line-rule) 0 0 var(--color-text-strong);    }    /*     * A diff. The hue agrees with the sign the line already starts with, + or -, which is part of the text     * and is what a reader copies; a removed line also steps back in ink.     */    &.code-line-added {      background: color-mix(in oklab, var(--color-success) 11%, transparent);      box-shadow: inset var(--code-line-rule) 0 0 var(--color-success);    }    &.code-line-removed {      background: color-mix(in oklab, var(--color-danger) 10%, transparent);      color: var(--color-text-body);      box-shadow: inset var(--code-line-rule) 0 0 var(--color-danger);    }    @media (forced-colors: active) {      &:is(.code-line-highlight, .code-line-added, .code-line-removed) {        outline: 1px solid Highlight;        outline-offset: -1px;      }    }  }  /*   * Numbered: each line counts itself in a quiet gutter that is not selected with the code. The gutter holds two   * digits; a listing of a hundred lines or more sets --code-gutter: 3ch, so every number ends on one edge.   */  .code-numbered {    --code-gutter: 2ch;    .code-line::before {      content: counter(code-line);      display: inline-block;      width: var(--code-gutter);      margin-inline-end: 1.25rem;      color: var(--color-text-disabled);      text-align: end;      user-select: none;      -webkit-user-select: none;    }    .code-line:is(.code-line-highlight, .code-line-added, .code-line-removed)::before {      color: var(--color-text-muted);    }    /* The gutter stays quieter than the code in forced colors, as a snippet's prompt does. */    @media (forced-colors: active) {      .code-line::before {        color: GrayText;      }    }  }  /*   * Panel: one well around a header and a block. The block inside gives up its own well; the header is a   * 40px strip over a hairline, with the name at the start and a control 4px in from the end.   */  .code-panel {    --code-radius: var(--radius-control);    display: flex;    flex-direction: column;    min-width: 0;    margin: 0;    border-radius: calc(var(--code-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    overflow: clip;    background: var(--color-surface-inset);    box-shadow: var(--shadow-pressed);    .code-block {      border-radius: 0;      background: transparent;      box-shadow: none;      &:focus-visible {        outline-offset: -2px;      }    }    .btn {      --btn-height: 2rem;      --btn-radius: calc(var(--code-radius) - 4px / var(--corner-scale));      --btn-font-size: .78125rem;      --btn-padding-x: .625rem;      --icon-size: .875rem;      --icon-offset: -.0625rem;      min-height: var(--btn-height);    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  .code-header {    display: flex;    flex: none;    align-items: center;    justify-content: space-between;    gap: .75rem;    min-height: 2.5rem;    padding-block: 0;    padding-inline: 1rem 4px;    border-block-end: 1px solid var(--color-line-hair);  }  /* The name of the file, or of the language. */  .code-title {    --icon-size: .875rem;    display: inline-flex;    align-items: center;    gap: .5rem;    min-width: 0;    margin: 0;    overflow: hidden;    color: var(--color-text-muted);    font: 400 .75rem/1.4 var(--font-family-mono);    font-variant-ligatures: none;    text-autospace: no-autospace;    text-spacing-trim: space-all;    text-overflow: ellipsis;    white-space: nowrap;  }}