К основному содержанию
скилл CX Codex

sizing-units — скилл для Claude Code: rem, px и когда что

Скилл sizing-units учит агента выбирать единицы измерения в CSS по смыслу: rem для текста, px для границ, относительные для контейнеров.

MIT 437 установок ★ 197 обновлён 2026-10-22

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add dembrandt/dembrandt-skills --skill sizing-units -a claude-code
Открыть на GitHub

Что делает sizing-units

Скилл объясняет, что единица — не оформление, а объявление поведения при увеличении текста. rem растёт вместе с текстом, px остаётся фиксированным, % и clamp() следуют за доступным местом. Агент ставит размеры шрифта, внутренние отступы кнопок и высоту контролов в rem, границы и тени — в px, а ширину контейнеров — в относительных единицах. Медиазапросы пишет в em, чтобы респектить настройку браузера.

Срабатывает на файлах дизайн-системы, токенах, tailwind.config.* и компонентах. Без FFmpeg и библиотек не требует. Проверяет, что контролы не обрезают текст на 200% масштабе браузера по WCAG 2.2 SC 1.4.4.

Какие задачи решает

  • выбрать единицу для отступов в дизайн-токенах
  • починить кнопки, которые режут текст при увеличении шрифта
  • написать медиазапросы, уважающие настройки пользователя
  • задать высоту контрола так, чтобы она росла с текстом
  • сверстать карточку, которая не сломается на крупном шрифте

Примеры запросов агенту

  • Какую единицу использовать для padding в кнопках?
  • Напиши spacing scale в tokens.css в правильных единицах
  • Почему карточка .card обрезает текст на 200% шрифте? Исправь

Как установить sizing-units

1Через Skills CLI (Vercel)

npx skills add dembrandt/dembrandt-skills --skill sizing-units -a claude-code

2Вручную: положить файлы

~/.claude/skills/sizing-units/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/sizing-units/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о sizing-units

Как установить sizing-units в Claude Code?

Выполни npx skills add dembrandt/dembrandt-skills --skill sizing-units -a claude-code, файл ляжет в ~/.claude/skills/sizing-units/SKILL.md.

Что делает sizing-units?

Учит агента выбирать CSS-единицы по назначению: rem для текста и его окружения, px для границ и теней, относительные для контейнеров. Показывает, где min-height вместо height и почему медиазапросы пишут в em.

Зачем sizing-units рекомендует em для медиазапросов?

em в медиазапросе следует за настройкой браузера: пользователь с крупным шрифтом по умолчанию получит мобильную вёрстку раньше, чем px-брейкпоинт, и текст не сломает макет.

Исходный текст

SKILL.md · MIT
---
name: sizing-units
description: rem, px or relative units for each kind of value. Use when defining spacing and sizing tokens, control heights or media queries, or when a layout breaks under enlarged text.
metadata:
  priority: 5
  pathPatterns:
    - "design-system/**"
    - "ui/**"
    - "**/tokens*"
    - "**/*.css"
    - "**/tailwind.config.*"
    - "components/**"
    - "src/components/**"
  promptSignals:
    phrases:
      - "rem"
      - "px"
      - "em"
      - "spacing scale"
      - "sizing tokens"
      - "root font size"
      - "text zoom"
      - "which unit"
retrieval:
  aliases:
    - px vs rem
    - css units
    - spacing units
    - sizing tokens
    - root font size
    - text scaling
  intents:
    - decide between px and rem for spacing
    - define a spacing scale
    - fix a layout that breaks when text is enlarged
    - choose units for media queries
    - set control heights that survive text scaling
  examples:
    - should spacing be in rem or px
    - our buttons clip when the user enlarges text
    - what unit for border radius and shadows
    - should media queries use px or em
---

# Sizing Units

## The Question the Unit Answers

A unit is not a formatting preference. It is a declaration of what happens to a value when the user enlarges text.

- `rem` — this value belongs to the text and must grow with it.
- `px` — this value belongs to the screen and must stay put.
- `%`, `fr`, `ch`, `clamp()`, `min()` — this value belongs to the available space.

Pick the unit by answering that question, not by picking a house style and applying it everywhere. Both absolutist positions — all-rem and all-px — produce defects, and they are different defects.

## Zoom Is Not the Font-Size Setting

The common argument for px everywhere is that browsers already have full-page zoom, so the root font size can be ignored. They are separate controls serving separate people.

- **Full-page zoom** magnifies everything, layout included. It buys larger text at the cost of horizontal scrolling and fewer items per screen.
- **The browser's default font size** enlarges text and leaves the layout alone. This is what a user with low vision sets once, years ago, and never touches again. They will not switch to zoom because your product ignored it.

A product that hard-codes every dimension in px answers the first user and silently refuses the second. WCAG 2.2 SC 1.4.4 (Resize Text) requires text to reach 200% without loss of content or function, and SC 1.4.10 (Reflow) requires the page to survive it in a single column. See [[wcag-accessibility]].

## Use rem For

**Typography.** Every font size and line height. See [[modular-scale-typography]].

**Padding around text.** A button's inner padding in px means large text presses against its edges. In rem the breathing room scales with the words it surrounds.

**Control heights.** A 40px control holding 24px text is broken. Write the height token in rem and it stays a control-shaped control at every text size. See [[component-family-consistency]].

**Measure.** `max-width` on a text column: `65ch` or a rem value, never px.

**Gaps between text-bearing blocks.** Stack spacing in a form or an article is part of the reading rhythm.

## Use px For

**Hairlines and borders.** `1px` is one device pixel by intent. In rem it becomes `1.25px` at a larger root size and renders as a blurry smear.

**Shadow offsets and blur.** Elevation is a screen-space effect. See [[elevation-and-depth]].

**Small icons inside controls** where the icon is a fixed glyph rather than text.

**Sub-pixel corrections** — the `-1px` that makes two borders overlap instead of doubling.

## Use Relative Units For

Layout widths and gaps. This is where the "lock it in px so it stays stable" instinct goes wrong: a px-locked container is not stable, it is brittle. The text inside it still grows, and a fixed box is exactly what makes growing text clip.

```css
/* Brittle — the box cannot absorb anything */
.card   { width: 320px; height: 180px; }
.sidebar { width: 280px; }

/* Resilient */
.card    { max-width: 20rem; min-height: 11.25rem; }
.sidebar { width: clamp(16rem, 22%, 22rem); }
```

**`min-height`, never `height`,** on anything containing text. A fixed height cannot grow; a minimum height holds the shape at rest and yields when it must.

## Media Queries

Use `em` in media queries. Media-query `rem` and `em` both resolve against the browser's default font size, ignoring any `html { font-size }` you set — so `em` is the honest spelling, and both respect the user's preference where a px breakpoint does not. A user with a large default font size gets the layout their effective text size warrants, not the one their device width claims.

```css
@media (min-width: 48em) { /* ~768px at default settings */ }
```

## Do Not Reset the Root

```css
html { font-size: 62.5%; } /* Do not do this */
```

The 62.5% trick exists to make rem arithmetic easy — `1.6rem` for 16px. It buys you mental arithmetic and pays for it by overriding the user's stated preference by default. Keep the root at the browser default and let the tooling do the division.

## A Measured Container Must Not Depend on What It Sizes

When script sizes an element from its container, the container's size must be definite and independent of that element on every breakpoint. If the container shrink-wraps the child, the measurement reads the child's own collapsed size and the element stays collapsed, silently, on the breakpoints where the chain loses its definite size. Give the chain a definite size down to the measured box and observe the box itself, not window events.

## Review Checklist

- [ ] Is every font size, line height, and text-adjacent padding in rem?
- [ ] Are borders, hairlines, and shadow offsets in px?
- [ ] Does any element containing text use `height` rather than `min-height`?
- [ ] Are container widths relative (`%`, `fr`, `clamp()`, `max-width`) rather than fixed px?
- [ ] Are media-query breakpoints in `em`?
- [ ] Is `html { font-size }` left at the browser default?
- [ ] At a 200% browser font-size setting, does every control still contain its label, with no clipping and no horizontal page scroll?
- [ ] Is every script-measured container sized by layout rather than by the child it sizes?

© dembrandt · MIT · dembrandt/dembrandt-skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
uncertainty-and-units K-Dense-AI uncertainty-and-units — скилл для Claude Code и Codex, который проверяет физические единицы и рассчитывает неопределённость измерений. Запускается при проверке научных вычислений или подозрительного результата. CX Codex +1 1 200установок accessible-animation iart-ai Скилл accessible-animation учит агента уважать prefers-reduced-motion: убирает опасное движение, но оставляет плавные переходы и подсказки интерфейса. CX Codex +1 4 400установок editorial typeui.sh Скилл editorial для Claude Code задаёт правила редакционного дизайна: серифная типографика, 8pt-сетка, токены цветов и проверки доступности. Покрывает вёрстку лонгридов и документации. CX Codex +1 3 300установок spacious typeui.sh Скилл spacious для Claude Code, Cursor, Codex и других ИИ-редакторов, который учит агента строить интерфейсы с щедрыми пробелами, последовательными отступами и сеткой 8 pt. CX Codex +1 2 800установок web-design-guidelines platform-design-skills Скилл web-design-guidelines для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode с правилами доступности и адаптивного веб-интерфейса. Подключается к задачам с HTML, CSS, WCAG, веб-компонентами и производительностью. CX Codex +1 1 600установок ui-design Mindrally Скилл ui-design для Claude Code задаёт агенту правила вёрстки и интерфейсов: доступность, адаптивность, производительность. Обеспечивает предсказуемый фронтенд. CX Codex +1 1 000установок

Из того же набора45

Весь набор →
coordinated-data-views Скилл coordinated-data-views для ИИ-кодинга, который подсказывает, как связать таблицу с картой, диаграммой или графиком и синхронизировать выделение в обе стороны. CX Codex +1 843установок tab-navigation Скилл tab-navigation для проектирования вкладок: подсказывает, когда они уместны, как устроена полоса вкладок и как ведёт себя клавиатура. CX Codex +1 842установок authentic-product-representation Скилл authentic-product-representation для Claude Code заменяет lorem ipsum реальными данными в лендингах и демо-панелях. Используется при вёрстке hero-блоков и скриншотов продукта. CX Codex +1 831установок domain-expert-configuration Скилл domain-expert-configuration для Claude Code помогает проектировать панели настроек для пользователей без технического бэкграунда. Включается в задачах о configuration, settings panel, solver или constraints. CX Codex +1 830установок app-shell Скилл app-shell для Claude Code задаёт правила для шапки, переключателя сервисов, сайдбара и строки статуса. Помогает упорядочить навигацию мультисервисных систем. CX Codex +1 504установок clone-website Скилл clone-website воссоздаёт живую страницу в Figma, Penpot или код с проверкой соответствия оригиналу. Снимает размеры, стили и контент с реального рендера, собирает макет по секциям и сверяет результат. CX Codex +1 411установок surface-separation Скилл surface-separation учит агента разделять карточки, панели и контейнеры одним способом — рамкой, тенью или заливкой — и держать прозрачность для состояний. CX Codex +1 378установок marketing-vs-product-system Скилл marketing-vs-product-system задаёт правила дизайн-токенов при расхождении лендинга и интерфейса сервиса. Помогает сохранить единый бренд при разной плотности экранов. CX Codex +1 373установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой