Skip to content

CSS3 Шпаргалка

Новейшее развитие CSS с модулями для стилизации, раскладки и анимации.

01

Селекторы

Селекторы атрибутов и псевдоклассы

CSS3 ввёл мощные селекторы атрибутов и псевдоклассы. ^= совпадает с префиксом, $= — с суффиксом, *= — с подстрокой. nth-child даёт чередующуюся раскраску строк без JavaScript.

css3
/* attribute selectors */
input[type="text"] { border: 1px solid blue; }
a[href^="https"] { color: green; }
a[href$=".pdf"] { color: red; }
a[href*="example"] { font-weight: bold; }

/* pseudo-classes */
a:visited { color: purple; }
li:first-child { font-weight: bold; }
li:nth-child(odd) { background: #f0f0f0; }
input:focus { outline: 2px solid blue; }

Структурные псевдоклассы

Структурные псевдоклассы выбирают элементы по их положению в DOM. :first-child / :last-child нацеливаются на края. nth-child(an+b) поддерживает формулы: 2n — чётные, 2n+1 — нечётные, 3n — каждый третий. :nth-of-type считает только соседей того же типа элемента. :empty совпадает с элементами без детей.

css3
/* positional pseudo-classes */
li:first-child { color: green; }
li:last-child { color: red; }
li:only-child { font-weight: bold; }

/* nth variants */
li:nth-child(3) { color: blue; }
li:nth-child(2n+1) { background: #eee; } /* odd */
li:nth-last-child(2) { color: orange; }

/* type-based */
p:first-of-type { font-size: 1.2em; }
p:nth-of-type(even) { color: gray; }
div:empty { display: none; }

:is, :where и :has

:is() и :where() группируют селекторы для краткости. Разница: :is() берёт наибольшую специфичность своих аргументов, а :where() всегда имеет нулевую специфичность — идеально для базовых стилей, которые легко переопределить. :has() — долгожданный родительский/реляционный селектор, позволяющий стилизовать элемент по его потомкам.

css3
/* :is() - matches any selector in the list */
:is(h1, h2, h3) { color: navy; }
:is(.btn, .link):hover { opacity: 0.8; }

/* :where() - same as :is but zero specificity */
:where(article, section) p { line-height: 1.6; }

/* :has() - parent selector (selects element that has a match) */
div:has(> img) { padding: 0; }
card:has(.badge) { border-color: gold; }
form:has(input:invalid) button { opacity: 0.5; }

Отрицание и псевдоклассы форм

:not() отрицает селектор и теперь принимает список. Псевдоклассы форм (:required, :valid, :invalid, :checked, :placeholder-shown, :in-range) позволяют стилизовать по состоянию поля без JavaScript — отлично для инлайн-валидации и кастомных checkbox/radio.

css3
/* :not() excludes matching elements */
input:not([type="checkbox"]) { display: block; }
li:not(:last-child) { border-bottom: 1px solid #ddd; }

/* form state pseudo-classes */
input:required { border-color: red; }
input:optional { border-color: #ccc; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:in-range { color: black; }
input:out-of-range { color: red; }
input:placeholder-shown { background: #fafafa; }
input:checked + label { font-weight: bold; }

Специфичность и каскад

Специфичность решает, какое правило применится при конфликте селекторов. Считайте ID, классы и элементы как (a,b,c). !important обходит каскад, но ломает сопровождаемость — избегайте его. При равной специфичности побеждает позднее правило в порядке следования. DevTools показывает вычисленный каскад.

css3
/* specificity ranking: inline > ID > class/attr/pseudo > type/element */
#nav .item { color: red; }     /* 1,1,0 */
.menu .item { color: blue; }   /* 0,2,0 */
li.item { color: green; }      /* 0,1,1 */

/* !important overrides normal declarations */
.btn { color: white !important; }

/* source order wins on equal specificity */
.late { color: purple; }  /* wins over .early */
02

Блочная модель

box-sizing

box-sizing: border-box включает padding и border в объявленные width/height, делая размеры предсказуемыми. content-box (по умолчанию) добавляет их сверху. Глобальное применение border-box — важнейший CSS-сброс: он устраняет самые частые головные боли с расчётом раскладки.

css3
/* default: width = content only */
.box-content { box-sizing: content-box; width: 200px; padding: 20px; } /* total 240px */

/* padding & border inside width */
.box-border { box-sizing: border-box; width: 200px; padding: 20px; border: 2px solid; } /* total 200px */

/* universal reset - apply everywhere */
*, *::before, *::after {
  box-sizing: border-box;
}

Margin и padding

Padding — внутри границы (наследует фон); margin — снаружи (прозрачный). Вертикальные margin соседних блочных элементов схлопываются до большего значения — горизонтальные никогда не схлопываются. margin: 0 auto центрирует блочный элемент с заданной шириной. Отрицательные margin могут подтягивать контент, но применяйте их умеренно.

css3
.box {
  /* top right bottom left (clockwise) */
  margin: 10px 20px 15px 25px;
  /* 2 values: vertical horizontal */
  padding: 10px 20px;
  /* single value: all sides */
  margin: 0 auto; /* horizontal centering for fixed-width block */
}

/* margin collapse (vertical only) */
.a { margin-bottom: 30px; }
.b { margin-top: 20px; }
/* gap between .a and .b = 30px, not 50px (collapsed to larger) */

/* negative margins pull elements together */
.pull-left { margin-left: -10px; }

box-shadow

Синтаксис box-shadow: offset-x offset-y blur-radius spread-radius color. Положительные смещения сдвигают тень вправо/вниз. inset создаёт внутреннюю тень. Несколько теней наслаиваются, первая сверху. Используйте rgba для полупрозрачных естественных теней. Жёсткие тени (нулевое размытие) дают плоский, графичный стиль.

css3
/* offset-x offset-y blur spread color */
.card { box-shadow: 0 4px 6px rgba(0,0,0,0.1); }

/* inset shadow (inside the box) */
.inset { box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }

/* multiple shadows (first = top layer) */
.layered { box-shadow: 0 1px 2px #000, 0 8px 24px rgba(0,0,0,0.15); }

/* no blur, hard shadow (neo-brutalism) */
.hard { box-shadow: 6px 6px 0 #000; }

/* glow effect */
.glow { box-shadow: 0 0 20px rgba(0,150,255,0.6); }

Типы display

display: none удаляет элемент из раскладки (место не резервируется). Блочные элементы занимают всю ширину и складываются вертикально; inline текут с текстом и игнорируют width/height. inline-block сочетает строчный поток с блочными размерами. flow-root очищает float без хаков clearfix. contents прячет сам блок, оставляя детей в раскладке.

css3
/* block: full width, new line */
div, p { display: block; }

/* inline: flows with text, ignores width/height */
span, a { display: inline; }

/* inline-block: flows inline but accepts width/height */
.tag { display: inline-block; width: 100px; }

/* none: removed from layout entirely */
.hidden { display: none; }

/* modern display values */
.flow { display: flow-root; } /* new block formatting context */
.contents { display: contents; } /* element's box disappears, children participate */

Overflow

overflow управляет содержимым, выходящим за пределы блока. visible (по умолчанию) позволяет выходить; hidden обрезает; auto добавляет прокрутку при необходимости; scroll показывает её всегда. clip (новее) похож на hidden, но запрещает любую прокрутку, даже через JS. overflow-y/x управляют осями независимо. Любое значение overflow, кроме visible, создаёт новый контекст форматирования.

css3
.scrollable {
  overflow: auto;       /* scrollbars when needed */
  overflow-y: scroll;   /* always show vertical scrollbar */
  overflow-x: hidden;   /* hide horizontal overflow */
}

/* visible (default) - content spills out */
.spill { overflow: visible; }

/* clip - like hidden but no programmatic scroll */
.clipped { overflow: clip; }

/* clip to a shape */
.custom-clip {
  overflow: clip;
  overflow-clip-margin: 20px;
}

/* longhand for both axes */
.both { overflow-x: hidden; overflow-y: auto; }
03

Flexbox

Flex-контейнер

display: flex превращает элемент в flex-контейнер. justify-content выравнивает элементы вдоль главной оси (горизонталь в row); align-items — вдоль поперечной. flex-wrap позволяет элементам переноситься на новые строки. gap заменяет хак с отступами через margin. Flexbox силён в одномерных раскладках (ряды или колонки).

css3
.container {
  display: flex;
  flex-direction: row;       /* row | row-reverse | column | column-reverse */
  justify-content: center;   /* main axis: flex-start | center | space-between | space-around | space-evenly */
  align-items: center;       /* cross axis: stretch | flex-start | center | baseline */
  flex-wrap: wrap;           /* nowrap | wrap | wrap-reverse */
  gap: 16px;                 /* spacing between items */
  align-content: space-between; /* multi-line spacing */
}

Flex-элементы

flex-grow управляет расширением элемента для заполнения свободного места (1 = равная доля). flex-shrink управляет сжатием. flex-basis — начальный размер. Сокращение flex: 1 означает равный рост от нулевой база — идеально для равных колонок. align-self переопределяет align-items контейнера для одного элемента. order меняет визуальный порядок без изменения порядка DOM.

css3
.item {
  flex-grow: 1;     /* grow to fill extra space (0 = don't grow) */
  flex-shrink: 1;   /* shrink when space is tight (0 = don't shrink) */
  flex-basis: 200px; /* initial size before growing/shrinking */
  
  /* shorthand: flex: grow shrink basis */
  flex: 1 1 200px;   /* flexible from 200px */
  flex: 1;            /* = 1 1 0% - equal distribution */
  flex: 0 0 250px;    /* fixed width, no grow/shrink */
  
  align-self: flex-end; /* override align-items for this item */
  order: 2;             /* visual reordering (default 0) */
}

Паттерны выравнивания flex

Flexbox делает центрирование тривиальным: justify-content: center + align-items: center. Прилипающий футер — flex-колонка body с min-height: 100vh и основным контентом с flex: 1. В навигационных панелях space-between прижимает первый и последний элементы к краям. Автоматические margin (margin-left: auto) — гибкая альтернатива justify-content для сдвига элементов.

css3
/* perfect centering */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

/* sticky footer: body is flex column */
body { display: flex; flex-direction: column; min-height: 100vh; }
main { flex: 1; } /* grows to fill, pushing footer down */

/* navbar: space between */
.nav { display: flex; justify-content: space-between; }

/* auto margins absorb space */
.push-right { margin-left: auto; }

Flex-wrap и адаптивная сетка

flex-wrap: wrap позволяет элементам переходить на новые строки, когда места не хватает. flex: 1 1 280px создаёт карточки, стартующие с 280px и растущие, заполняя ряд. Так получается адаптивная сетка карточек без медиазапросов. Осторожно: элементы последнего ряда растягиваются, что может выглядеть неровно — для однородных сеток карточек часто лучше CSS Grid.

css3
.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.card {
  /* start at 280px, grow & shrink fluidly */
  flex: 1 1 280px;
  /* prevent stretching beyond readable width */
  max-width: 100%;
}

/* OR fixed-width cards that wrap */
.card-fixed {
  flex: 0 0 300px;
}

/* last row items stretch to fill - to avoid, use grid instead */
/* gap wraps with items automatically */

flex-direction и оси

flex-direction определяет главную ось. В row (по умолчанию) justify-content управляет горизонтальным выравниванием; в column — вертикальным: оси меняются местами. Всегда спрашивайте себя «какая здесь главная ось?» при выравнивании. row-reverse и column-reverse меняют порядок элементов, что также влияет на распределение места justify-content.

css3
/* row: main axis = horizontal */
.row { display: flex; flex-direction: row; justify-content: center; }

/* column: main axis = vertical (axes swap!) */
.col { display: flex; flex-direction: column; align-items: center; }

/* reverse order */
.reverse { display: flex; flex-direction: row-reverse; }

/* centering in column: justify-content centers vertically */
.col-center {
  display: flex;
  flex-direction: column;
  justify-content: center; /* vertical center */
  align-items: center;     /* horizontal center */
}
04

Grid Layout

Grid-контейнер

display: grid создаёт двумерную раскладку. grid-template-columns определяет дорожки колонок; единица fr распределяет свободное место пропорционально. repeat(auto-fit, minmax(200px, 1fr)) — магический рецепт адаптивных сеток: колонки создаются и масштабируются сами, без медиазапросов. gap чисто добавляет пространство между дорожками.

css3
.grid {
  display: grid;
  /* fixed columns */
  grid-template-columns: 200px 1fr 200px;
  /* responsive auto columns */
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-template-rows: auto 1fr auto;
  gap: 20px;            /* row + column gap */
  row-gap: 20px;        /* gap between rows */
  column-gap: 16px;     /* gap between columns */
}

Grid-template-areas

grid-template-areas позволяет рисовать раскладку визуально именованными областями — предельно читаемо. Каждая строка в кавычках — ряд; имена размещают элементы, точка — пустая ячейка. Элемент с grid-area: name занимает эту область. Самый понятный способ строить раскладки уровня страницы вроде каркаса приложения.

css3
.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

/* empty cell with a dot */
grid-template-areas: "header header" "sidebar .";

Размещение grid-элементов

Grid-элементы можно размещать явно по номерам линий. grid-column: 1 / 3 тянется от линии 1 до линии 3 (охватывая 2 колонки). Ключевое слово span задаёт размер числом дорожек. Линии можно именовать в grid-template-columns для читаемости. Без явного размещения элементы автоматически заполняют доступные ячейки.

css3
.item {
  /* place by line numbers: row-start / col-start / row-end / col-end */
  grid-column: 1 / 3;      /* span columns 1 to 3 */
  grid-row: 1 / 2;
  
  /* span keyword */
  grid-column: span 2;     /* span 2 columns */
  grid-row: 2 / span 3;
  
  /* shorthand: grid-area: row-start / col-start / row-end / col-end */
  grid-area: 1 / 1 / 3 / 4;
  
  /* name a line and reference it */
  grid-column-start: content-start;
}

Выравнивание в grid

Выравнивание grid работает на двух уровнях. justify-content/align-content позиционируют всю сетку в контейнере при наличии свободного места. justify-items/align-items выравнивают элементы внутри их ячеек (по умолчанию stretch). justify-self/align-self переопределяют выравнивание для отдельного элемента. «justify» — строчная/главная ось, «align» — блочная/поперечная.

css3
.grid {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  
  /* align tracks within container */
  justify-content: center;  /* center the grid horizontally */
  align-content: center;    /* center vertically (needs fixed height) */
  
  /* align items within their cells */
  justify-items: stretch;   /* fill cell width (default) */
  align-items: center;      /* center within cell height */
}

.item {
  justify-self: start;      /* override justify-items for one item */
  align-self: end;
}

auto-fit против auto-fill

Оба создают столько дорожек, сколько помещается, но ведут себя по-разному при малом числе элементов. auto-fit сворачивает неиспользуемые дорожки и растягивает элементы, заполняя ряд. auto-fill сохраняет пустые дорожки, поэтому элементы остаются минимального размера. auto-fit — когда элементы должны расти и заполнять пространство; auto-fill — когда нужен фиксированный, однородный размер элементов.

css3
/* auto-fit: empty tracks collapse, items stretch to fill */
.autofit {
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

/* auto-fill: empty tracks remain, items keep their size */
.autofill {
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}

/* with few items:
   auto-fit -> items stretch to fill the row
   auto-fill -> items stay small, leaving empty columns */
05

Позиционирование

Значения position

static — значение по умолчанию. relative смещает элемент от его обычной позиции в потоке (место сохраняется). absolute выводит его из потока и позиционирует относительно ближайшего позиционированного предка (или вьюпорта). fixed привязан к вьюпорту браузера. sticky переключается между relative и fixed в зависимости от прокрутки — идеально для прилипающих шапок.

css3
/* static - default, flows normally */
.static { position: static; }

/* relative - offset from its normal position */
.relative { position: relative; top: 10px; left: 20px; }

/* absolute - positioned relative to nearest positioned ancestor */
.absolute { position: absolute; top: 0; right: 0; }

/* fixed - positioned relative to viewport (stays on scroll) */
.fixed { position: fixed; bottom: 0; left: 0; }

/* sticky - relative until scroll threshold, then fixed */
.sticky { position: sticky; top: 0; }

Абсолютное центрирование

Есть несколько способов абсолютно центрировать. Трюк с translate(-50%, -50%) работает с элементами любого размера. Техника inset: 0 + margin: auto требует явных размеров. Современный подход — display: grid с place-items: center (сокращение align-items + justify-items) — без позиционных вычислений и самый простой метод.

css3
/* classic: position absolute + transform */
.center {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

/* inset: 0 + margin: auto (needs width/height) */
.center-auto {
  position: absolute;
  inset: 0;          /* top/right/bottom/left: 0 */
  margin: auto;
  width: 300px;
  height: 200px;
}

/* modern: no positioning needed */
.center-grid { display: grid; place-items: center; }

Позиционирование sticky

position: sticky удерживает элемент в обычном потоке до порога (например, top: 0), затем прилипает как fixed. Идеально для прилипающих шапок или оглавления в сайдбаре. Подводный камень: любой предок с overflow: hidden/auto/scroll (в направлении прокрутки) становится содержащим блоком и ломает ожидаемое поведение. Всегда задавайте sticky-элементам фон и z-index.

css3
.header {
  position: sticky;
  top: 0;            /* sticks when header hits top of viewport */
  z-index: 100;
  background: white;
}

/* sticky sidebar that scrolls with content until threshold */
.sidebar {
  position: sticky;
  top: 60px;         /* offset below the fixed header */
  max-height: calc(100vh - 60px);
  overflow-y: auto;
}

/* NOTE: a parent with overflow: hidden breaks sticky */

z-index и контексты наложения

z-index работает только на позиционированных (не static) элементах. Контекст наложения создают position + z-index, а также opacity < 1, transform, filter, will-change и isolation: isolate. Внутри контекста наложения z-index детей изолирован — ребёнок никогда не отрисуется выше соседа своего предка. Понимание этого предотвращает эскалационные войны z-index.

css3
.modal { position: fixed; z-index: 1000; }
.overlay { position: fixed; z-index: 999; }
.card { position: relative; z-index: 1; }

/* creating a stacking context (isolates z-index) */
.context {
  position: relative;
  z-index: 0;  /* children's z-index only matters within this */
}

/* other properties that create stacking contexts:
   opacity < 1, transform, filter, will-change, isolation: isolate */
.isolated { isolation: isolate; }

Сокращение inset

inset — логическое сокращение для top, right, bottom и left — как margin/padding принимает 1, 2 или 4 значения. inset: 0 растягивает абсолютно позиционированный элемент на весь содержащий блок. Чище, чем четыре отдельных свойства, и хорошо сочетается с margin: auto для центрирования.

css3
/* inset sets top right bottom left (like margin) */
.popup {
  position: absolute;
  inset: 0;          /* all sides = 0 (stretches to fill parent) */
}

/* two values: vertical horizontal */
.pill {
  position: absolute;
  inset: 10px 20px;  /* top/bottom 10px, left/right 20px */
}

/* four values: top right bottom left */
.box {
  position: absolute;
  inset: 10px 20px 30px 40px;
}

/* longhand equivalents */
.inset-longhand {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}
06

Стилизация текста

Свойства шрифта

font-family всегда должна заканчиваться обобщённым семейством (serif, sans-serif, monospace) как последним рубежом. font-weight — диапазон 100-900; типичные: 400 обычный, 700 жирный. line-height лучше задавать без единиц (1.5), чтобы он масштабировался с font-size. Сокращение font требует size и family; порядок: style, weight, size/line-height, family.

css3
body {
  font-family: "Helvetica Neue", Arial, sans-serif; /* fallback chain */
  font-size: 16px;
  font-weight: 400;     /* 100-900; 400=normal, 700=bold */
  font-style: italic;   /* normal | italic | oblique */
  line-height: 1.5;     /* unitless = multiplier of font-size */
  letter-spacing: 0.5px;
  word-spacing: 2px;
  font-variant: small-caps;
}

/* shorthand: style weight size/line-height family (order matters) */
p { font: italic 700 16px/1.5 "Georgia", serif; }

Форматирование текста

text-align: justify может создавать «реки» пробелов; в паре с hyphens: auto блоки выглядят чище. text-decoration теперь принимает line, style и color одним сокращением. text-transform: capitalize делает заглавной первую букву каждого слова. white-space: nowrap запрещает перенос. text-shadow принимает offset-x offset-y blur color.

css3
.text {
  text-align: justify;          /* left | right | center | justify */
  text-decoration: underline wavy red; /* line style color */
  text-decoration: line-through;
  text-transform: uppercase;    /* lowercase | capitalize */
  text-indent: 2em;             /* first-line indent */
  white-space: nowrap;          /* prevent wrapping */
  word-break: break-word;       /* break long words */
  hyphens: auto;                /* auto-hyphenate (needs lang attr) */
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

Переполнение текста и многоточие

Однострочному усечению нужны три свойства: white-space: nowrap, overflow: hidden, text-overflow: ellipsis. Для многострочного усечения используйте -webkit-line-clamp с display: -webkit-box (префикс -webkit- всё ещё нужен, но работает во всех современных браузерах). Для срабатывания усечения требуется max-width или width.

css3
.truncate {
  /* three properties required for ellipsis */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;    /* clip | ellipsis */
  max-width: 200px;
}

/* multi-line clamp (line-clamp) */
.clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;       /* limit to 3 lines */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* custom fade effect */
.fade {
  -webkit-mask-image: linear-gradient(to bottom, black 70%, transparent);
}

text-shadow и эффекты

text-shadow принимает offset-x offset-y blur-radius color. Несколько теней наслаиваются, первая сверху — полезно для неоновых свечений или контура текста (тень в 4 направления имитирует обводку). В отличие от -webkit-text-stroke, text-shadow поддерживается повсеместно. Жёсткие тени (без размытия) дают ретро-стилистику «стикера».

css3
/* x-offset y-offset blur color */
.shadow { text-shadow: 2px 2px 4px rgba(0,0,0,0.3); }

/* multiple shadows (first = top) */
.neon { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #0ff; }

/* 3D letterpress effect */
.letterpress { text-shadow: 0 1px 0 rgba(255,255,255,0.5); }

/* outline text (no blur, light color) */
.outline { text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; }

/* hard shadow retro effect */
.retro { text-shadow: 4px 4px 0 #ff6b6b; }

Режимы письма и направление

writing-mode управляет направлением текста: horizontal-tb (по умолчанию), vertical-rl (например, традиционный китайский/японский) или vertical-lr. direction: rtl обслуживает языки с письмом справа налево, например арабский. Логические свойства (margin-inline-start, padding-block, inset-inline-end) адаптируются к режиму письма и направлению автоматически — необходимы для по-настоящему интернациональных раскладок, не зависящих от направления.

css3
/* horizontal (default) */
.horizontal { writing-mode: horizontal-tb; }

/* vertical, top to bottom */
.vertical-rl { writing-mode: vertical-rl; }
.vertical-lr { writing-mode: vertical-lr; }

/* text direction */
.rtl { direction: rtl; unicode-bidi: bidi-override; }

/* logical properties adapt to writing mode */
.box {
  margin-inline-start: 10px;   /* logical left in LTR */
  padding-block: 20px;         /* logical top/bottom */
  inset-inline-end: 0;         /* logical right in LTR */
}
07

Фоны и градиенты

Сокращение background

Сокращение background принимает все свойства фона. При совместном использовании position и size разделяйте их слэшем (center/cover). Несколько фонов наслаиваются через запятую, объявленный первым — верхний. Сплошной цвет всегда указывайте последним как запасной вариант. cover заполняет блок, contain вмещает изображение целиком.

css3
.box {
  /* longhand */
  background-color: #fff;
  background-image: url("bg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
  
  /* shorthand (color image position/size repeat attachment) */
  background: #fff url("bg.png") center/cover no-repeat fixed;
}

/* multiple backgrounds (first = top layer) */
.multi {
  background: url("top.png") top left/contain no-repeat,
              url("bottom.png") bottom right/cover no-repeat #eee;
}

Линейные градиенты

linear-gradient(direction, color-stops) создаёт плавный переход. Направление — ключевое слово (to right) или угол (45deg). Остановки могут включать позиции в процентах — две остановки на одной позиции дают резкую границу (отлично для полос). Градиенты — это изображения: они задаются в background-image и применяются везде, где допустимы изображения.

css3
/* direction or angle, then color stops */
.gradient { background: linear-gradient(to right, red, blue); }
.gradient-45 { background: linear-gradient(45deg, red, blue); }

/* multiple color stops */
.rainbow { background: linear-gradient(to right, red, orange, yellow, green, blue); }

/* color stops with positions */
.hard-stop { background: linear-gradient(to right, red 0%, red 50%, blue 50%, blue 100%); }

/* transparent stops for fade effects */
.fade { background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent); }

Радиальные и конические градиенты

radial-gradient расходится от центра — полезно для прожекторов и кнопок. Центр можно позиционировать (at top left) и управлять формой/размером (circle, closest-side). conic-gradient вращает цвета вокруг точки — идеален для pie-диаграмм и цветовых кругов. Резкие остановки в коническом градиенте дают чистые «дольки».

css3
/* radial: radiates from a center point */
.radial { background: radial-gradient(circle, red, blue); }
.radial-c { background: radial-gradient(circle at top left, #fff, #000); }
.radial-size { background: radial-gradient(closest-side, red, blue); }

/* conic: rotates around a center point */
.pie { background: conic-gradient(red 0% 30%, blue 30% 70%, green 70% 100%); }

/* conic with angle start */
.spin { background: conic-gradient(from 45deg, red, yellow, green, red); }

background-clip и origin

background-clip определяет, насколько далеко простирается фон: border-box (по умолчанию, под границей), padding-box (внутри границы) или content-box (внутри padding). Известный трюк с заголовками: background-clip: text с color: transparent заливает текст градиентом или изображением. Для Safari всегда добавляйте версию с префиксом -webkit-. background-origin задаёт область позиционирования.

css3
/* clip: where the background paints */
.border-box { background-clip: border-box; } /* default - under border */
.padding-box { background-clip: padding-box; } /* inside border */
.content-box { background-clip: content-box; } /* inside padding */

/* text clip: gradient-filled text */
.gradient-text {
  background: linear-gradient(to right, red, blue);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
}

/* origin: where positioning starts */
.origin { background-origin: content-box; }

background-attachment и параллакс

background-attachment: fixed создаёт параллакс — фон неподвижен, контент прокручивается над ним. scroll (по умолчанию) движется с элементом; local прокручивается вместе с содержимым элемента (удобно для прокручиваемых боксов). Fixed-привязка на мобильных дёргается и плохо поддерживается; для продакшен-параллакса используйте transform: translate3d по позиции прокрутки.

css3
/* fixed: background stays put during scroll (parallax) */
.parallax {
  background-image: url("hero.jpg");
  background-attachment: fixed;
  background-size: cover;
  height: 100vh;
}

/* scroll: scrolls with element (default) */
.scroll { background-attachment: scroll; }

/* local: scrolls with element's content */
.local {
  background-attachment: local; /* scrolls with inner content */
}

/* NOTE: background-attachment: fixed has poor mobile support
   prefer transform-based parallax for mobile */
08

Границы и скругления

border-radius

border-radius скругляет углы, принимая 1-4 значения (по часовой от левого верхнего). Слэш разделяет горизонтальный/вертикальный радиусы для эллиптических углов. border-radius: 50% на квадрате создаёт идеальный круг; на прямоугольнике — эллипс. Полные свойства (border-top-left-radius) управляют отдельными углами. Скруглённые углы обрезают фон, границы и (с overflow: hidden) дочерний контент.

css3
.box { border-radius: 10px; }              /* all corners */
.box-2 { border-radius: 10px 20px; }        /* top-left/bottom-right  top-right/bottom-left */
.box-4 { border-radius: 10px 20px 30px 40px; } /* TL TR BR BL (clockwise) */

/* per-corner longhand */
.card {
  border-top-left-radius: 10px;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 30px;
  border-bottom-left-radius: 40px;
}

/* elliptical corners (horizontal / vertical) */
.ellipse { border-radius: 50px / 25px; }

/* perfect circle (square element) */
.circle { border-radius: 50%; }

border-image

border-image разрезает изображение на 9 областей и применяет углы/края к границе. border-image-slice делит исходное изображение; repeat управляет мозаикой краёв. Современный трюк: border-image с linear-gradient и slice 1 создаёт градиентные границы. Учтите: border-image заменяет border-style, поэтому сначала задайте border-width.

css3
.frame {
  border: 20px solid transparent;
  border-image-source: url("frame.png");
  border-image-slice: 30;        /* slice image into 9 regions */
  border-image-width: 20px;
  border-image-outset: 0;
  border-image-repeat: stretch;  /* stretch | repeat | round | space */
}

/* shorthand */
.frame-shorthand {
  border: 20px solid transparent;
  border-image: url("frame.png") 30 stretch;
}

/* gradient border (using border-image) */
.grad-border {
  border: 4px solid;
  border-image: linear-gradient(to right, red, blue) 1;
}

Несколько границ

CSS не умеет складывать несколько border, но есть обходные пути. box-shadow с нулевым offset и spread создаёт чёткие внешние границы (работает с border-radius). outline рисует вторую границу снаружи, но игнорирует border-radius. Псевдоэлемент даёт полный контроль, включая радиус. У каждого способа свои компромиссы — выбирайте по тому, нужны ли скруглённые углы.

css3
/* technique 1: box-shadow (no rounded issue) */
.multi-shadow {
  box-shadow: 0 0 0 5px red, 0 0 0 10px blue;
}

/* technique 2: outline (outside border, no radius) */
.outline-border {
  border: 5px solid red;
  outline: 5px solid blue;
  outline-offset: 0;
}

/* technique 3: pseudo-element (full control) */
.pseudo-border {
  position: relative;
  border: 5px solid red;
}
.pseudo-border::after {
  content: "";
  position: absolute;
  inset: -10px;
  border: 5px solid blue;
  border-radius: inherit;
}

Градиентные границы

Градиентные границы — задача хитрая, ведь border-image не поддерживает border-radius. Надёжное решение: два слоя фона — сплошной цвет с clip до padding-box и градиент с clip до border-box, с прозрачной границей. Это уважает border-radius и работает везде. Более простой метод через border-image подходит, когда скругления не нужны.

css3
/* method 1: border-image (works but no border-radius) */
.grad-1 {
  border: 4px solid;
  border-image: linear-gradient(to right, red, blue) 1;
}

/* method 2: background-clip trick (works with radius) */
.grad-2 {
  border: 4px solid transparent;
  border-radius: 12px;
  background:
    linear-gradient(white, white) padding-box,
    linear-gradient(to right, red, blue) border-box;
}

/* method 3: mask + pseudo (advanced, supports radius + animation) */

Outline и стили фокуса

outline рисуется снаружи границы и не влияет на раскладку — идеален для индикаторов фокуса. outline-offset добавляет зазор. Критическое правило доступности: никогда не задавайте outline: none без видимой альтернативы. :focus-visible показывает обводку только при навигации с клавиатуры (не кликом мыши) — современный, удобный для пользователя подход к стилизации фокуса.

css3
/* outline: doesn't affect layout, draws outside border */
.focusable:focus {
  outline: 2px solid blue;
  outline-offset: 2px;  /* gap between element and outline */
}

/* never use outline: none without a replacement */
button:focus { outline: none; box-shadow: 0 0 0 3px rgba(0,150,255,0.5); }

/* :focus-visible: only shows outline for keyboard users */
button:focus-visible { outline: 2px solid blue; outline-offset: 2px; }
button:focus:not(:focus-visible) { outline: none; }

/* outline shorthand */
.box { outline: 2px dashed red; }
09

Трансформации

2D-трансформации

2D-трансформации — translate, rotate, scale, skew — перемещают и искажают элементы, не влияя на раскладку (соседи не пересчитываются). Комбинации применяются справа налево, поэтому порядок важен: rotate перед translate движет вдоль повёрнутой оси. Поскольку трансформации не вызывают reflow, они идеальны для анимаций и ускоряются GPU.

css3
.box { transform: translate(50px, 20px); }   /* move right 50, down 20 */
.box-x { transform: translateX(50px); }
.box-scale { transform: scale(1.5); }          /* grow 1.5x */
.box-scale-2 { transform: scale(1, 2); }       /* x 1, y 2 */
.box-rotate { transform: rotate(45deg); }      /* clockwise */
.box-skew { transform: skew(20deg, 10deg); }   /* skew x, y */

/* combine transforms (order matters!) */
.combo { transform: translate(20px, 0) rotate(45deg) scale(1.2); }

/* transform does NOT affect layout (no reflow) */

transform-origin

transform-origin задаёт точку опоры трансформаций — по умолчанию центр элемента. Принимает ключевые слова (top left), пиксели или проценты. Изменение опоры резко меняет поведение поворота и масштабирования: карточка, переворачивающаяся вокруг верхнего края, требует transform-origin: top. Для 3D-трансформаций можно указать третье значение по оси z.

css3
.box { transform: rotate(45deg); }

/* default origin: center center (50% 50%) */
.center { transform-origin: center center; }

/* rotate around top-left corner */
.tl { transform-origin: top left; transform: rotate(45deg); }

/* custom point (x y) */
.custom { transform-origin: 20px 50px; transform: rotate(45deg); }

/* 3-value form (x y z) */
.three-d { transform-origin: 0 0 100px; }

/* percentage-based */
.pct { transform-origin: 100% 0; } /* top-right corner */

3D-трансформации

3D-трансформации добавляют rotateX, rotateY, rotateZ, translateZ и scaleZ. perspective(n) должна быть первой функцией трансформации (или применяться к родителю), чтобы включить глубину — меньшие значения усиливают 3D-эффект. translate3d и scale3d ускоряются GPU и в анимациях работают лучше 2D-аналогов.

css3
.card { transform: perspective(1000px) rotateY(45deg); }

/* rotateX/Y/Z - rotate around 3D axes */
.flip { transform: rotateX(180deg); }   /* flip horizontally */
.turn { transform: rotateY(180deg); }   /* flip like a page */
.spin { transform: rotateZ(90deg); }    /* same as rotate() */

/* translate3d (GPU-accelerated) */
.move { transform: translate3d(50px, 20px, 100px); }

/* scale3d */
.grow { transform: scale3d(1.5, 1.5, 1.5); }

/* combined 3D */
.combo-3d { transform: perspective(800px) rotateX(15deg) rotateY(-20deg) translateZ(-50px); }

Перспектива и 3D-пространство

perspective определяет дистанцию наблюдателя — меньше = драматичнее 3D. Задайте её на родителе, чтобы все дети делили одну точку схода. transform-style: preserve-3d позволяет вложенным элементам жить в общем 3D-пространстве (необходимо для кубов). backface-visibility: hidden скрывает обратную сторону элемента — ключ к эффектам flip-card.

css3
/* perspective on parent: applies to all children uniformly */
.scene { perspective: 1000px; }
.cube { transform: rotateY(45deg); }

/* perspective() in transform: only affects that element */
.solo { transform: perspective(1000px) rotateY(45deg); }

/* perspective-origin: vanishing point */
.scene { perspective: 1000px; perspective-origin: top left; }

/* transform-style: preserve-3d lets children share 3D space */
.cube {
  transform-style: preserve-3d;
  transform: rotateY(30deg);
}
.cube .face { position: absolute; transform: translateZ(50px); }

/* backface-visibility: hide back of flipped element */
.card { backface-visibility: hidden; }

Анимация трансформаций (производительность)

Анимируйте только transform и opacity — они ускоряются GPU и не вызывают layout (reflow) или paint. Анимация top/left/width/margin заставляет браузер пересчитывать раскладку на каждом кадре, вызывая рывки. will-change: transform подсказывает браузеру заранее подготовить композитный слой, но злоупотребление расходует память. Применяйте прямо перед анимацией и снимайте после.

css3
/* GOOD: animate transform & opacity (GPU-accelerated) */
.smooth {
  transition: transform 0.3s ease;
}
.smooth:hover { transform: translateY(-5px); }

/* BAD: animating top/left triggers reflow */
.janky { transition: top 0.3s; }
.janky:hover { top: -5px; }

/* will-change: hint the browser to optimize */
.prepared {
  will-change: transform;  /* prepare for upcoming transform changes */
}

/* force GPU layer (use sparingly) */
.gpu { transform: translateZ(0); }
10

Переходы (Transitions)

Сокращение transition

transition: property duration timing-function delay. Значение по умолчанию — all 0s ease 0s, поэтому просто transition: 0.3s анимирует все изменённые свойства. Ради производительности и контроля перечисляйте конкретные свойства. Несколько переходов разделяются запятой. Переход задаётся на базовом состоянии элемента (не :hover), чтобы обратная анимация тоже играла.

css3
.btn {
  background: blue;
  /* shorthand: property duration timing-function delay */
  transition: background 0.3s ease 0s;
  
  /* common usage */
  transition: all 0.3s ease;
  
  /* multiple properties (comma-separated) */
  transition: background 0.3s, transform 0.2s ease-out;
  
  /* list the same duration on many properties */
  transition: 0.3s;
}

.btn:hover {
  background: darkblue;
  transform: scale(1.05);
}

Функции тайминга

Функции тайминга управляют ускорением. ease (по умолчанию) — плавная. ease-out ощущается наиболее отзывчиво для UI (быстрый старт, медленный финиш). linear ощущается неестественно для большинства движений. cubic-bezier(x1,y1,x2,y2) позволяет создать свою кривую — значения вне 0-1 по оси y дают перелёт/отскок. steps(n) создаёт дискретные скачки — полезно для анимаций из спрайт-листов.

css3
.ease { transition: all 0.3s ease; }              /* default, smooth start/end */
.linear { transition: all 0.3s linear; }          /* constant speed */
.ease-in { transition: all 0.3s ease-in; }        /* slow start */
.ease-out { transition: all 0.3s ease-out; }      /* slow end (feels responsive) */
.ease-in-out { transition: all 0.3s ease-in-out; }/* slow both ends */

/* cubic-bezier: custom curve (P1x P1y P2x P2y) */
.custom { transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55); } /* overshoot */

/* steps: jump in increments */
.steps { transition: all 0.3s steps(4, end); }

Множественные и каскадные переходы

Разные свойства могут иметь разные длительности и задержки — полезно для хореографии, когда одно свойство заканчивается до старта другого. transition-delay создаёт каскадные появления для списков; в паре с nth-child задержка каждого элемента нарастает. Задержки работают и на выходе, но осторожно: если пользователь увёл курсор посреди задержки, появление может резко оборваться.

css3
.card {
  /* different durations per property */
  transition: transform 0.2s ease-out, box-shadow 0.4s ease;
  
  /* delay creates staggered effect */
  transition: background 0.3s, color 0.3s 0.1s; /* color starts after 0.1s */
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  background: #f5f5f5;
}

/* stagger multiple elements via transition-delay */
.item:nth-child(1) { transition-delay: 0s; }
.item:nth-child(2) { transition-delay: 0.1s; }
.item:nth-child(3) { transition-delay: 0.2s; }

Анимируемые свойства

Одни свойства переходят плавно, другие вызывают рывки. GPU-звёзды — transform, opacity и filter. Цвета и box-shadow допустимы (вызывают paint, но не layout). Избегайте переходов по width, height, margin, top, left — они заставляют пересчитывать раскладку на каждом кадре. Для анимации размера используйте transform: scale().

css3
/* WELL-SUPPORTED & performant */
.good {
  transition: transform 0.3s, opacity 0.3s, filter 0.3s;
}

/* OK but may trigger paint */
.okay {
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
  transition: box-shadow 0.3s;
}

/* AVOID: triggers layout (reflow) - janky */
.bad {
  transition: width 0.3s, height 0.3s, margin 0.3s, top 0.3s, left 0.3s;
}

/* if you must animate size, use transform: scale() instead */
.smooth-resize { transition: transform 0.3s; }

Триггеры переходов

Переходы запускаются любым изменением свойства: состояниями псевдоклассов (:hover, :focus, :checked), сменой классов (добавленных/удалённых JS) и изменениями медиазапросов. Они плавно интерполируют между старым и новым значениями. Переходы работают в обе стороны (вход/выход). Для более сложного, циклического или многошагового движения используйте анимации @keyframes.

css3
/* hover trigger */
.btn { transition: all 0.3s; }
.btn:hover { transform: scale(1.1); }

/* focus trigger (accessibility-friendly) */
.input { transition: border-color 0.2s; }
.input:focus { border-color: blue; }

/* class change via JavaScript */
.modal { transition: opacity 0.3s; opacity: 0; }
.modal.open { opacity: 1; }

/* media query trigger */
.box { transition: width 0.3s; width: 100%; }
@media (min-width: 768px) { .box { width: 50%; } }

/* CSS state triggers (:checked) */
.toggle:checked + .menu { transition: max-height 0.3s; max-height: 500px; }
11

Анимации

@keyframes

@keyframes определяет последовательность анимации. Остановки — в процентах (0%, 50%, 100%) или from/to (эквивалент 0%/100%). Свойства, не указанные в остановке, интерполируются между заданными. Работают только анимируемые свойства (transform, opacity, цвета) — display, position и т. п. нет. Определите @keyframes один раз и переиспользуйте на многих элементах.

css3
@keyframes bounce {
  0%   { transform: translateY(0); }
  50%  { transform: translateY(-30px); }
  100% { transform: translateY(0); }
}

/* from/to shorthand (2-stop) */
@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

/* multiple properties at each stop */
@keyframes pulse {
  0%   { opacity: 1; transform: scale(1); }
  50%  { opacity: 0.5; transform: scale(1.1); }
  100% { opacity: 1; transform: scale(1); }
}

Сокращение animation

Сокращение animation упаковывает 8 свойств в этом порядке: name, duration, timing-function, delay, iteration-count, direction, fill-mode, play-state. Минимум нужны name и duration. Заметьте: значение времени без единиц двусмысленно — первое время это duration, второе — delay. Для читаемости в продакшене предпочитайте полные свойства или частичное сокращение.

css3
.bouncing {
  /* longhand */
  animation-name: bounce;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-delay: 0s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-fill-mode: both;
  animation-play-state: running;
  
  /* shorthand: name duration timing delay count direction fill-mode play-state */
  animation: bounce 1s ease-in-out 0s infinite alternate both running;
  
  /* minimal: name + duration */
  animation: bounce 1s;
}

Итерации и направление

animation-iteration-count управляет повторами — infinite крутит вечно, дробные значения проигрывают частичный цикл. animation-direction: alternate играет анимацию вперёд, затем назад на следующей итерации, создавая бесшовный отскок. reverse играет назад, alternate-reverse стартует назад. Alternate обязателен для маятниковых движений вроде пульса или «дыхания».

css3
/* iteration-count: how many times to play */
.once { animation-iteration-count: 1; }    /* default */
.thrice { animation-iteration-count: 3; }
.forever { animation-iteration-count: infinite; }
.fractional { animation-iteration-count: 0.5; } /* half a play */

/* direction */
.normal { animation-direction: normal; }       /* 0% -> 100% */
.reverse { animation-direction: reverse; }     /* 100% -> 0% */
.alternate { animation-direction: alternate; } /* forward, then backward */
.alternate-rev { animation-direction: alternate-reverse; }

animation-fill-mode

animation-fill-mode управляет стилями до и после анимации. none (по умолчанию) возвращает обычные стили элемента. forwards удерживает финальное состояние кейфреймов после завершения — необходимо для анимаций появления, чтобы элементы не отскакивали назад. backwards применяет первый кейфрейм во время задержки. both покрывает оба случая. Для одноразовых появлений используйте forwards или both.

css3
@keyframes slideIn {
  from { transform: translateX(-100%); }
  to   { transform: translateX(0); }
}

/* none (default): reverts to original styles before/after */
.none { animation: slideIn 1s; }

/* forwards: holds the final (to) state after finishing */
.forwards { animation: slideIn 1s forwards; }

/* backwards: applies the (from) state during delay */
.backwards { animation: slideIn 1s 0.5s backwards; }

/* both: applies from during delay AND holds to after */
.both { animation: slideIn 1s 0.5s both; }

Состояние воспроизведения и пауза

animation-play-state: paused замораживает анимацию на текущем кадре; running возобновляет. Это самый чистый способ паузы при наведении или через класс, переключаемый JS — анимация помнит позицию, а не перезапускается. Ради производительности ставьте на паузу анимации элементов, ушедших из вида, через IntersectionObserver. Сочетайте с медиазапросами reduced-motion для доступности.

css3
.anim { animation: spin 2s linear infinite; }

/* pause on hover */
.anim:hover { animation-play-state: paused; }

/* pause via class (JS toggle) */
.anim.paused { animation-play-state: paused; }

/* useful for performance: pause off-screen animations */
.offscreen { animation-play-state: paused; }

/* resume */
.resumed { animation-play-state: running; }
12

Медиазапросы

Базовый синтаксис

Медиазапросы применяют стили условно. (min-width: 768px) — mobile-first: применяется на экранах от 768px. Комбинируйте с and (оба условия), запятыми (ИЛИ) и not (отрицание). Подход mobile-first (min-width) предпочтителен: базовые стили для маленьких экранов, затем наращивание для больших. Так CSS для маленьких экранов остаётся лёгким.

css3
/* apply styles when viewport is at least 768px wide */
@media (min-width: 768px) {
  .grid { grid-template-columns: repeat(2, 1fr); }
}

/* combine conditions with and */
@media (min-width: 768px) and (max-width: 1024px) {
  .box { padding: 20px; }
}

/* list of queries (OR) */
@media (max-width: 600px), (min-width: 1200px) {
  .text { font-size: 14px; }
}

/* negate with not */
@media not print {
  .screen-only { display: block; }
}

Брейкпоинты по min/max width

Брейкпоинты должны опираться на контент, а не на конкретные устройства, но привычные диапазоны работают хорошо: 640px (планшет), 1024px (десктоп), 1280px (большой). Mobile-first означает min-width и мобильные стили как базу. Новый синтаксис диапазонов (width >= 768px) читабельнее и поддерживается всеми современными браузерами, заменяя громоздкие комбинации min/max.

css3
/* common breakpoints (mobile-first) */
/* base styles (mobile) */
.container { padding: 16px; }

@media (min-width: 640px)  { /* small tablets */ 
  .container { padding: 24px; }
}
@media (min-width: 1024px) { /* desktops */
  .container { padding: 32px; max-width: 1200px; margin: 0 auto; }
}
@media (min-width: 1280px) { /* large screens */
  .container { max-width: 1400px; }
}

/* range syntax (newer, cleaner) */
@media (width >= 768px) and (width <= 1024px) {
  .box { padding: 20px; }
}

Ориентация и соотношение сторон

Помимо ширины, медиазапросы нацеливаются на ориентацию (portrait/landscape), aspect-ratio, возможность hover и тип указателя. @media (hover: hover) гарантирует, что hover-стили применяются только на устройствах с реальным указателем (избегая «липкого» hover на тач). (pointer: coarse) нацелен на тач-устройства — отлично для увеличения целей нажатия. Эти возможности дают интерфейсы, действительно подходящие устройству.

css3
/* portrait vs landscape */
@media (orientation: portrait) {
  .grid { grid-template-columns: 1fr; }
}
@media (orientation: landscape) {
  .grid { grid-template-columns: 1fr 1fr; }
}

/* aspect ratio */
@media (min-aspect-ratio: 16/9) {
  .video { width: 100%; height: auto; }
}

/* hover capability: devices that support hover */
@media (hover: hover) {
  .btn:hover { background: darkblue; }
}

/* pointer: fine (mouse) vs coarse (touch) */
@media (pointer: coarse) {
  .btn { padding: 16px 32px; } /* bigger tap targets */
}

Стили печати

Медиазапрос print оформляет страницы для печати. Скрывайте навигацию, рекламу и интерактивные элементы; растягивайте контент на всю ширину; принуждайте чёрный-на-белом для экономии чернил. break-inside: avoid не даёт элементам разрываться между страницами, break-before: page принуждает разрыв страницы. Трюк ::after на ссылках раскрывает URL при печати — бесценно для печатаемых статей.

css3
@media print {
  /* hide non-essential UI */
  .nav, .sidebar, .ads, .comments { display: none; }
  
  /* expand main content */
  .main { width: 100%; margin: 0; }
  
  /* force black text on white */
  body { color: black; background: white; }
  
  /* avoid breaking inside elements */
  h1, h2, img, table { break-inside: avoid; }
  
  /* page breaks before sections */
  h1 { break-before: page; }
  
  /* show URLs after links */
  a[href]::after { content: " (" attr(href) ")"; }
}

prefers-reduced-motion и color-scheme

prefers-reduced-motion — критическая функция доступности: пользователям с вестибулярными нарушениями нужно минимум движения. Всегда предлагайте fallback с укороченными или отключёнными анимациями. prefers-color-scheme позволяет автоматически подстраиваться под тему ОС пользователя. Для тёмной темы также продумайте контраст, изображения и тени, работающие на тёмном фоне.

css3
/* respect users who prefer less motion */
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

/* light/dark mode */
@media (prefers-color-scheme: dark) {
  body { background: #1a1a1a; color: #eee; }
  .card { background: #2a2a2a; }
}

@media (prefers-color-scheme: light) {
  body { background: white; color: #333; }
}
13

Адаптивный дизайн

Жидкая типографика с clamp()

clamp(min, preferred, max) создаёт значения, плавно масштабирующиеся между границами — идеально для типографики и отступов, адаптирующихся без медиазапросов. Предпочтительное значение обычно выражение на базе vw. Это устраняет множество брейкпоинтов. Сочетайте с rem ради доступности (пользователи всё ещё могут масштабировать корневой размер шрифта). Жидкая типографика улучшает ощущаемую производительность и читаемость на всех устройствах.

css3
/* clamp(min, preferred, max) - fluid between bounds */
h1 {
  /* scales from 1.5rem to 3rem as viewport grows */
  font-size: clamp(1.5rem, 5vw, 3rem);
}

p {
  /* readable body text on any screen */
  font-size: clamp(1rem, 2.5vw, 1.25rem);
}

/* fluid spacing */
.section {
  padding: clamp(1rem, 4vw, 3rem);
}

/* fluid container width */
.container {
  width: clamp(280px, 90vw, 1200px);
  margin: 0 auto;
}

Подход mobile-first

Mobile-first означает базовые стили для маленьких экранов, затем min-width-медиазапросы для наращивания на больших. Получается более лёгкий CSS (мобильные скачивают только нужное) и мышление с приоритетом контента. Desktop-first (max-width) заставляет мобильные устройства скачивать и переопределять десктопные стили — медленнее и труднее в сопровождении.

css3
/* base = mobile styles (no media query) */
.card {
  width: 100%;
  padding: 12px;
  font-size: 14px;
}

/* progressively enhance for larger screens */
@media (min-width: 640px) {
  .card { width: 50%; padding: 16px; }
}

@media (min-width: 1024px) {
  .card { width: 33.33%; padding: 24px; font-size: 16px; }
}

/* AVOID desktop-first (forces mobile to override) */
/* @media (max-width: 640px) { ... } */

Container Queries

Container queries меняют правила игры: компоненты реагируют на размер родителя, а не вьюпорта. Карточка может перестраивать раскладку и в узком сайдбаре, и в широкой основной области — настоящая адаптивность на уровне компонента. container-type: inline-size делает запросы по ширине (самый производительный вариант). Именуйте контейнеры для точного таргетинга или используйте безымянные запросы для ближайшего предка.

css3
/* make an element a query container */
.sidebar {
  container-type: inline-size;
  container-name: sidebar;
}

/* styles based on the container's size, not the viewport */
@container sidebar (min-width: 400px) {
  .card {
    grid-template-columns: 1fr 1fr;
  }
}

/* inline-size = width only (most common, performant) */
/* size = both dimensions (more expensive) */

/* unnamed container query (uses nearest ancestor) */
.card-wrap { container-type: inline-size; }
@container (min-width: 500px) {
  .card { flex-direction: row; }
}

Единицы вьюпорта

vh/vw — проценты вьюпорта. Проблема: 100vh на мобильных меняется при показе/скрытии адресной строки, вызывая рывки. Новые единицы svh/lvh/dvh решают это — dvh обновляется динамически, svh использует наименьшее стабильное значение. vmin/vmax — меньшая/бо́льшая сторона вьюпорта — удобно для квадратных элементов, которые масштабируются. Размеры шрифта в vw всегда ограничивайте снизу rem/px через calc или clamp.

css3
.hero {
  height: 100vh;        /* full viewport height */
  /* small viewport units: account for mobile browser chrome */
  height: 100svh;       /* smallest possible viewport (stable) */
  height: 100lvh;       /* largest possible viewport */
  height: 100dvh;       /* dynamic - updates as chrome shows/hides */
}

.full-width { width: 100vw; }
.responsive-font { font-size: 5vw; }

/* vmin/vmax: smaller/larger of width or height */
.square { width: 50vmin; height: 50vmin; }
.banner { height: 30vmax; }

/* combining with calc for safety */
.hero-text { font-size: calc(16px + 2vw); }

aspect-ratio

aspect-ratio автоматически поддерживает соотношение width:height — больше никаких хаков с padding-top для адаптивного видео. Высота элемента выводится из ширины (или наоборот). В сочетании с object-fit: cover на изображениях это предотвращает сдвиг раскладки при загрузке. Самый чистый способ зарезервировать место под медиа и избежать cumulative layout shift (CLS) — метрики Core Web Vitals.

css3
/* maintain a 16:9 ratio regardless of width */
.video {
  aspect-ratio: 16 / 9;
  width: 100%;
}

/* square avatar */
.avatar {
  aspect-ratio: 1;
  width: 80px;
  border-radius: 50%;
}

/* golden ratio card */
.card {
  aspect-ratio: 1.618;
}

/* combined with object-fit for responsive images */
.thumb {
  aspect-ratio: 4 / 3;
  width: 100%;
  object-fit: cover;
}
14

Пользовательские свойства (переменные)

Определение и использование переменных

CSS-переменные объявляются как --name и используются как var(--name). Определите их на :root для глобального доступа или ограничьте любым элементом. В отличие от переменных препроцессоров, они «живые»: изменение переменной мгновенно обновляет все использования, они каскадируются и наследуются. var() принимает запасное значение вторым аргументом, применяемое, когда переменная не определена.

css3
:root {
  --primary: #3490dc;
  --spacing: 16px;
  --max-width: 1200px;
}

.button {
  background: var(--primary);
  padding: var(--spacing);
  /* with fallback value (used if --primary undefined) */
  color: var(--text-color, #333);
}

/* override in a specific scope */
.dark-theme {
  --primary: #5a9fee;
}

Темизация и тёмная тема

Пользовательские свойства делают темизацию тривиальной: определите семантические переменные (--bg, --text, --primary), затем переопределите их в селекторе [data-theme]. Переключение атрибута data-theme на <html> мгновенно меняет всю тему — без дублирования стилей. Сочетайте с prefers-color-scheme для автоматической тёмной темы с учётом ручного выбора пользователя. Это современный и производительный способ темизации.

css3
:root {
  --bg: #ffffff;
  --text: #1a1a1a;
  --primary: #3490dc;
}

[data-theme="dark"] {
  --bg: #1a1a1a;
  --text: #ffffff;
  --primary: #5a9fee;
}

body {
  background: var(--bg);
  color: var(--text);
}

/* auto dark mode via media query */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #1a1a1a;
    --text: #ffffff;
  }
}

Каскад и наследование

Пользовательские свойства каскадируют и наследуются как обычный CSS. Переменная на .card доступна .card и всем потомкам — но не соседям. Каждый элемент читает вычисленное значение переменной в своей области. @property (новее) позволяет объявлять типизированные переменные с syntax, начальным значением и флагом наследования — это включает плавные переходы и анимации пользовательских свойств.

css3
:root { --color: blue; }       /* global */
.card { --color: green; }      /* scoped to .card */
.card .inner { color: var(--color); } /* green - inherits from .card */

/* variables inherit like other properties */
.parent { --size: 20px; }
.child { font-size: var(--size); } /* 20px via inheritance */

/* but: each element reads its own computed value */
.a { --x: 10px; }
.b { /* --x is NOT defined here, even if .a is sibling */ }

/* @property: typed variables with initial value */
@property --angle {
  syntax: "<angle>";
  inherits: false;
  initial-value: 0deg;
}

Взаимодействие с JavaScript

CSS-переменные полностью доступны из JavaScript. Чтение: getComputedStyle(el).getPropertyValue('--name') (возвращает строку, часто с ведущим пробелом — обрезайте). Запись: el.style.setProperty('--name', value). Это делает переменные мощным мостом JS→CSS: обновите переменную в JS, и CSS отреагирует мгновенно — идеально для эффектов по прокрутке, темизации и динамических раскладок.

css3
/* read a variable */
const styles = getComputedStyle(document.documentElement);
const primary = styles.getPropertyValue("--primary"); /* "#3490dc" */

/* set a variable globally */
document.documentElement.style.setProperty("--primary", "#ff0000");

/* set on a specific element */
el.style.setProperty("--spacing", "24px");

/* inline style with variable */
<div style="--rotate: 45deg"></div>

/* useful pattern: expose JS values to CSS */
.root { --scroll: 0; }
.box { transform: rotate(calc(var(--scroll) * 1deg)); }

Запасные значения и цепочки

var() поддерживает запасное значение вторым аргументом, используемое только когда переменная не определена (не при невалидном значении — невалидное значение откатывает всё свойство к умолчанию). Запасные значения можно цеплять: var(--a, var(--b, #default)). Полезно для прогрессивного улучшения и интеграции сторонних компонентов. Поддержку проверяйте через @supports (--x: 0), хотя все современные браузеры поддерживают переменные.

css3
.box {
  /* single fallback */
  color: var(--undefined, #333);
  
  /* chained: try --primary, fall back to --blue, then #00f */
  color: var(--primary, var(--blue, #0000ff));
  
  /* fallback in calc() */
  width: calc(100% - var(--sidebar, 250px));
  
  /* invalid values fall back to inherited/default */
  /* var() itself doesn't fail — the property does */
}

/* feature detection for custom property support */
@supports (--custom: property) {
  :root { --modern: true; }
}
15

Фильтры

Функции filter

filter применяет визуальные эффекты к элементу. brightness/contrast/saturate принимают множители (1 = норма) или проценты. hue-rotate сдвигает все оттенки на угол. Несколько фильтров применяются слева направо. Типичные сценарии: черно-белые изображения при наведении, винтажные фото, затемнение фона. Фильтры затрагивают элемент, его фон, границы и детей.

css3
.blur { filter: blur(4px); }              /* gaussian blur in px */
.bright { filter: brightness(1.5); }     /* 1 = normal, >1 brighter */
.contrast { filter: contrast(200%); }    /* 100% = normal */
.gray { filter: grayscale(100%); }       /* 0-100% */
.sepia { filter: sepia(80%); }
.hue { filter: hue-rotate(90deg); }      /* rotate hue */
.invert { filter: invert(100%); }        /* invert colors */
.saturate { filter: saturate(2); }       /* 1 = normal */
.opacity { filter: opacity(50%); }

/* combine multiple filters (left-to-right) */
.vintage { filter: sepia(60%) contrast(110%) brightness(90%) saturate(1.2); }

drop-shadow

drop-shadow — аналог box-shadow среди фильтров, но он следует реальной альфа-форме элемента, а не его блоку. Значит, тени обнимают вырезы PNG/SVG и неправильные формы. Используйте для теней иконок, светящихся логотипов или любых непрямоугольных элементов. Несколько drop-shadow можно наслаивать. Учтите: может быть дороже box-shadow, применяйте обдуманно.

css3
/* drop-shadow follows the alpha shape (unlike box-shadow) */
.cutout {
  filter: drop-shadow(4px 4px 8px rgba(0,0,0,0.4));
}

/* shadows on PNG with transparency - hugs the shape */
.logo {
  filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));
}

/* glow effect on text or SVG */
.icon {
  filter: drop-shadow(0 0 8px rgba(0, 150, 255, 0.8));
}

/* multiple drop-shadows layer */
.deep {
  filter: drop-shadow(0 1px 1px rgba(0,0,0,0.5))
          drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

backdrop-filter

backdrop-filter применяет фильтр ко всему позади элемента — визитная карточка глассморфизма. Полупрозрачный фон плюс backdrop-filter: blur() даёт вид матового стекла. Для Safari всегда добавляйте префикс -webkit-. Чтобы эффект был виден, фон элемента должен быть частично прозрачным. Сочетайте с saturate() для сочного результата и добавьте лёгкую границу, имитирующую отражение на кромке.

css3
/* frosted glass effect */
.glass {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px); /* Safari */
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* saturate + blur for vivid glass */
.vivid-glass {
  backdrop-filter: blur(16px) saturate(180%);
}

/* dark glass for dark mode */
.dark-glass {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(12px);
}

Комбинирование фильтров

Несколько фильтров применяются слева направо, поэтому порядок влияет на результат (grayscale перед hue-rotate оставит нечего вращать). Фильтры анимируемы и ускоряются GPU — отлично для эффектов наведения. Сочетайте filter с mix-blend-mode, чтобы смешивать элемент с фоном. Для динамического управления храните цепочку фильтров в переменной и обновляйте через JS.

css3
/* order matters: each filter feeds the next */
.artsy {
  filter: grayscale(100%) contrast(150%) brightness(110%);
}

/* animate filters smoothly */
img { transition: filter 0.3s; }
img:hover { filter: grayscale(0%) saturate(1.4); }

/* use CSS variables for dynamic filters */
.dynamic { filter: var(--photo-filter, none); }

/* layer with other effects */
.complex {
  filter: blur(1px) brightness(1.1);
  mix-blend-mode: multiply;
  opacity: 0.9;
}

Производительность фильтров

Фильтры ускоряются GPU, но не бесплатны. Большое размытие на полноэкранных элементах вызывает тяжёлые перерисовки и рывки, особенно на мобильных. Держите радиусы blur маленькими, ограничивайте фильтруемую область и применяйте will-change: filter перед запуском анимаций. backdrop-filter особенно дорог — на маленьких элементах UI, а не на целых секциях. contain: paint изолирует область перерисовки для лучшей производительности.

css3
/* AVOID: large blur on full-screen elements */
.janky { filter: blur(20px); } /* causes repaints */

/* BETTER: pre-blurred image, or limit blur area */
.smooth {
  filter: blur(2px); /* small radius is cheaper */
}

/* backdrop-filter is expensive - use sparingly */
/* contain: paint can limit repaint area */
.contained {
  contain: paint;
  backdrop-filter: blur(10px);
}

/* will-change prepares the GPU layer */
.prepared {
  will-change: filter;
  filter: blur(4px);
}
16

Псевдоэлементы

::before и ::after

::before и ::after вставляют сгенерированный контент до/после фактического содержимого элемента. Свойство content обязательно (даже пустая строка для декоративных элементов). Контент может быть текстом, экранированным Unicode или значением атрибута через attr(). Эти псевдоэлементы по умолчанию строчные — задайте display: block для декораций в виде блоков. Идеальны для иконок, декоративных линий, цитат и очистки float.

css3
.quote::before { content: "\201C"; }  /* opening quote */
.quote::after  { content: "\201D"; }  /* closing quote */

/* icon via Unicode */
.warning::before { content: "\26A0"; margin-right: 6px; }

/* decorative element with content: "" */
.card::after {
  content: "";
  display: block;
  width: 50px; height: 2px;
  background: currentColor;
  margin-top: 12px;
}

/* content can use attributes */
a[href^="http"]::after {
  content: " (" attr(href) ")";
  font-size: 0.8em;
}

::first-letter и ::first-line

::first-letter стилизует первый символ — отлично для буквиц в статьях. ::first-line стилизует первую отформатированную строку, динамически меняясь при изменении ширины вьюпорта. Оба работают только на блочных элементах. Учтите: ::first-letter применяется, только когда первый символ не предваряется другим контентом (например, изображением). Это типографические основы редакционных раскладок.

css3
article p::first-letter {
  font-size: 3em;
  font-weight: bold;
  float: left;
  line-height: 0.8;
  margin-right: 8px;
  /* drop cap effect */
}

article p::first-line {
  text-transform: uppercase;
  letter-spacing: 1px;
  font-weight: bold;
}

/* only works on block-level elements */
/* affects the first formatted line (reflows with width) */

::selection

::selection стилизует выделенный пользователем текст. Применяются лишь несколько свойств: color, background-color, text-shadow и text-decoration. Используйте, чтобы брендировать цвет выделения под сайт. Применяйте глобально через ::selection или ограничивайте конкретными элементами. Старому Firefox нужен был ::-moz-selection, но современный Firefox поддерживает стандартный ::selection.

css3
/* style highlighted/selected text */
::selection {
  background: #b3d4fc;
  color: black;
  text-shadow: none;
}

/* scoped to specific elements */
p::selection { background: yellow; }
.highlight::selection { background: gold; color: #333; }

/* note: only a few properties work:
   color, background-color, text-shadow, 
   text-decoration (and its longhands) */

/* firefox historically used ::-moz-selection */

::placeholder и ::marker

::placeholder стилизует текст-подсказку в полях формы — задайте opacity: 1, потому что Firefox по умолчанию делает placeholder полупрозрачным. ::marker оформляет маркеры или номера пунктов списка и поддерживает ограниченный набор свойств (color, content, font, direction). Маркеры можно заменить своим контентом (Unicode, счётчики). Эти псевдоэлементы отдают оформление форм и списков под полный контроль дизайнера.

css3
/* style input placeholder text */
input::placeholder {
  color: #999;
  font-style: italic;
  opacity: 1; /* Firefox applies opacity < 1 by default */
}

/* style list item markers (bullets/numbers) */
ul li::marker {
  color: red;
  font-size: 1.2em;
  content: "\25CF"; /* custom bullet */
}

ol li::marker {
  content: counter(list-item) ". ";
  color: blue;
  font-weight: bold;
}

/* ::marker supports: color, content, font properties,
   direction, unicode-bidi, text-transform, white-space */

Сгенерированный контент и счётчики

Сгенерированный контент через ::before/::after может включать значения counter(), атрибуты (attr()) или строковые литералы — позволяя нумерацию, иконки и тултипы только на CSS, без лишнего DOM. counters() создаёт вложенную нумерацию вроде «1.2.3». Тултипы на attr(data-tooltip) с hover-переходом — лёгкая альтернатива JS-библиотекам. Помните: сгенерированный контент не в DOM и не читается некоторыми скринридерами — не размещайте там критичный контент.

css3
/* counter in generated content */
h2::before {
  content: "Section " counter(section) ": ";
  color: gray;
}

/* attr() reads HTML attributes */
a::after {
  content: attr(data-icon);
}

/* counters() for nested numbering */
ol { counter-reset: item; }
li { display: block; }
li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
}

/* CSS-only tooltip */
.tooltip::after {
  content: attr(data-tooltip);
  position: absolute;
  background: black; color: white;
  padding: 4px 8px;
  opacity: 0; transition: opacity 0.2s;
}
.tooltip:hover::after { opacity: 1; }
17

Счётчики

counter-reset и counter-increment

CSS-счётчики позволяют нумеровать элементы без JavaScript. counter-reset инициализирует счётчик (по умолчанию 0, но можно стартовать с другого значения). counter-increment увеличивает его (по умолчанию на 1, но подойдёт любое целое — даже отрицательное). Выводите значение через counter() внутри content. Счётчики ограничены элементом, на котором сброшены, и его потомками — это даёт вложенную нумерацию.

css3
body { counter-reset: section; }   /* initialize to 0 */

h2 {
  counter-increment: section;  /* +1 each h2 */
}

h2::before {
  content: "Section " counter(section) ": ";
}

/* custom increment value */
ol { counter-reset: item; }
li { counter-increment: item 1; }  /* +1 (default) */
li.big { counter-increment: item 2; } /* +2 */

/* reset to a custom starting value */
.start-5 { counter-reset: item 4; } /* next increment = 5 */

Функция counter()

counter(name) выводит текущее значение счётчика, а counter(name, style) применяет стиль списка: decimal (по умолчанию), lower/upper-alpha, lower/upper-roman, disc, square и другие. Можно вести несколько счётчиков параллельно и комбинировать их в content — идеально для рисунков с нумерацией по главам (Рисунок 3-2). Значения счётчиков вычисляются при рендере и обновляются автоматически при изменении DOM.

css3
body { counter-reset: section; }
h2 { counter-increment: section; }
h2::before {
  content: "Chapter " counter(section) ". ";
  color: navy;
}

/* counter style (decimal, lower-alpha, upper-roman, etc.) */
h2::before {
  content: counter(section, upper-roman) ". ";
}

/* multiple counters */
body { counter-reset: section figure; }
h2 { counter-increment: section; }
figcaption { counter-increment: figure; }
figcaption::before {
  content: "Figure " counter(section) "-" counter(figure) ": ";
}

Вложенные счётчики с counters()

counters(name, separator) — функция вложенных счётчиков: она соединяет значения счётчика на каждом уровне предков, разделяя заданной строкой. Так автоматически получаются структуры вроде «1.2.3» — один и тот же счётчик сбрасывается в каждом вложенном <ol>. Без counters() (множественного числа) вложенные списки делили бы общую нумерацию. Разделитель — любая строка, например '.' или '-'.

css3
ol { counter-reset: item; list-style: none; }
li::before {
  counter-increment: item;
  /* counters() concatenates ancestor counters with separator */
  content: counters(item, ".") " ";
}

/* produces: 1 / 1.1 / 1.2 / 2 / 2.1 / 2.1.1 ... */
<ol>
  <li>Item
    <ol>
      <li>Sub-item</li>
      <li>Sub-item</li>
    </ol>
  </li>
  <li>Item</li>
</ol>

/* custom separator */
li::before { content: counters(item, "-") ": "; }

Стилизация счётчиков

Счётчики поддерживают множество встроенных стилей: decimal, upper-roman, lower-alpha, lower-greek, cjk-decimal и другие. @counter-style позволяет определять свои стили с набором символов, системой (cyclic, additive, extends) и опциями вроде pad (ведущие нули), prefix/suffix и range. Отлично для тематизированных списков, эмодзи-маркеров или локализованной нумерации без JavaScript.

css3
/* built-in styles */
.decimal { content: counter(c, decimal); }
.roman { content: counter(c, upper-roman); }       /* I, II, III */
.alpha { content: counter(c, lower-alpha); }        /* a, b, c */
.greek { content: counter(c, lower-greek); }        /* alpha, beta, gamma */
.cjk { content: counter(c, cjk-decimal); }          /* CJK numerals */

/* @counter-style: define a custom style */
@counter-style thumbs {
  system: cyclic;
  symbols: "\1F44D"; /* thumbs up emoji */
  suffix: " ";
}
.like-list { list-style-type: thumbs; }

/* leading zeros via pad */
@counter-style padded {
  system: extends decimal;
  pad: 3 "0"; /* 001, 002, ... */
}

Практические паттерны счётчиков

Счётчики сильны в нумерованных шагах, оглавлениях и схемах. Оформите ::before круглым бейджем с цветом и номером — получите пошаговые списки без ручной нумерации. Правка DOM обновляет номера автоматически. Ограничение: значения счётчиков трудно прочитать из JavaScript — они только для отображения. Для логики на основе счёта используйте JS или CSS :nth-child.

css3
/* numbered steps */
.steps { counter-reset: step; }
.steps li { counter-increment: step; }
.steps li::before {
  content: counter(step);
  display: inline-block;
  width: 28px; height: 28px;
  border-radius: 50%;
  background: var(--primary);
  color: white;
  text-align: center;
  line-height: 28px;
  margin-right: 10px;
}

/* "you've completed N sections" via counters (limited - 
   counters can't be read by JS easily, use them for display) */
18

Многоколоночная раскладка

column-count и column-width

Многоколоночная раскладка распределяет контент по газетоподобным колонкам. column-count фиксирует число; column-width позволяет браузеру создать столько колонок по 250px, сколько помещается (адаптивно без медиазапросов). Сокращение columns принимает count и/или width. Многоколоночность идеальна для длинных текстов, но осторожно: короткий контент даёт неровные высоты колонок.

css3
.article {
  /* fixed number of columns */
  column-count: 3;
  
  /* OR width-based (browser decides count) */
  column-width: 250px;
  
  /* shorthand (count width) */
  columns: 3 250px;
  columns: 3;       /* 3 columns */
  columns: 250px;   /* 250px columns, auto count */
}

/* responsive: width lets columns collapse on small screens */
.fluid { column-width: 200px; } /* 1 column on mobile, more on desktop */

column-gap и column-rule

column-gap задаёт пространство между колонками (сейчас используется и flexbox, и grid). column-rule рисует вертикальную линию-разделитель в зазоре — это «колоночный» аналог border с тем же сокращением. Линия не занимает дополнительную ширину; она центрируется в зазоре. Используйте спокойный цвет, чтобы разграничить колонки, не отвлекая.

css3
.article {
  column-count: 3;
  column-gap: 30px;          /* space between columns */
  
  /* divider line (like border) */
  column-rule: 1px solid #ddd; /* shorthand */
  column-rule-width: 1px;
  column-rule-style: solid;
  column-rule-color: #ddd;
}

/* rule sits in the gap, doesn't add width */

column-span

column-span: all заставляет элемент прервать все колонки — идеально для журнального заголовка во всю ширину с колонками выше и ниже. column-span: none (по умолчанию) сохраняет поток через колонки. Учтите: это может вызвать значительный reflow и поддержка была непоследовательной; тестируйте тщательно. Надёжнее всего для заголовков между колонками.

css3
.article {
  column-count: 3;
}

/* heading spans all columns (like a magazine) */
.article h2 {
  column-span: all;
  /* resets above the heading, columns resume below */
}

/* default: content flows through columns */
.normal { column-span: none; }

/* note: column-span: all can cause reflow and is 
   not supported in older Firefox */

break-inside и разрывы колонок

В многоколоночном контенте элементы могут неудачно разрываться между колонками. break-inside: avoid удерживает элемент (карточку, figure) целиком в одной колонке. break-before/break-after: column принуждают разрыв колонки. Старые свойства page-break-* работают как псевдонимы. Распространённым хаком было display: inline-block с width: 100%, но break-inside: avoid — современный правильный подход.

css3
/* prevent an element from splitting across columns */
.card {
  break-inside: avoid;        /* modern */
  -webkit-column-break-inside: avoid; /* old webkit */
  page-break-inside: avoid;   /* old */
  display: inline-block;      /* hack for older browsers */
  width: 100%;
}

/* control where columns break */
h2 { break-after: column; }   /* force new column after */
h3 { break-before: column; }  /* force new column before */
p  { break-inside: avoid; }   /* keep paragraph together */

column-fill и балансировка

column-fill управляет распределением контента по колонкам. balance (по умолчанию) выравнивает высоты, чтобы колонки заканчивались примерно одинаково — визуально аккуратно. auto заполняет первую колонку полностью, прежде чем перейти к следующей, и требует фиксированной высоты; так ведёт себя печать. Балансные колонки приятнее для общего случая; auto лучше, когда контент должен течь строго сверху вниз.

css3
.article {
  column-count: 3;
  
  /* balance: equalize column heights (default in most browsers) */
  column-fill: balance;
  
  /* auto: fill first column fully, then next (needs height) */
  column-fill: auto;
  height: 500px; /* required for auto */
}

/* balanced columns look neat but can split awkwardly;
   auto is more like print, fills top-to-bottom */
19

Пользовательский интерфейс

Outline и доступность

Видимые индикаторы фокуса — требование доступности. :focus-visible показывает обводку только пользователям клавиатуры (не мыши) — лучшая практика стилизации фокуса. Никогда не задавайте outline: none без замены (например, кольца box-shadow). outline-offset добавляет воздуха между элементом и обводкой. Современные браузеры поддерживают скруглённые outline: border-radius влияет на форму обводки.

css3
/* visible focus ring for keyboard users */
button:focus-visible {
  outline: 2px solid #0066cc;
  outline-offset: 2px;
}

/* never outline: none without a replacement */
/* custom focus ring via box-shadow */
button:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.5);
}

/* outline shorthand */
.outlined { outline: 2px dashed red; outline-offset: 4px; }

/* thick rounded outline (modern browsers) */
button:focus-visible {
  outline: 3px solid blue;
  outline-offset: 2px;
  border-radius: 4px;
}

resize

resize определяет, может ли пользователь перетаскиванием менять размер элемента. textarea по умолчанию растягивается; resize: none отключает. vertical/horizontal/both ограничивают направление. Для работы resize элементу нужен overflow, отличный от visible (задайте overflow: auto или hidden). Полезно для textarea, редакторов кода и любых панелей, регулируемых пользователем.

css3
textarea {
  /* allow vertical resize only (default for textarea) */
  resize: vertical;
  
  /* allow both axes */
  resize: both;
  
  /* horizontal only */
  resize: horizontal;
  
  /* disable resizing */
  .locked { resize: none; }
  
  /* default: inline/block elements can't be resized;
     textarea default is both in most browsers */
}

/* note: resize only works on overflow != visible */

caret-color и user-select

caret-color задаёт цвет мигающего курсора в редактируемых элементах — мелочь, но приятная деталь брендированных форм. user-select управляет возможностью выделения текста: none отключает (для контролов UI), all выделяет весь элемент по клику (хорошо для блоков кода или адресов), contain удерживает выделение внутри элемента. Не ставьте user-select: none на body — это вредит доступности.

css3
/* color of the text cursor in inputs */
input, textarea {
  caret-color: #0066cc;  /* default: current color */
}

/* custom thick caret (limited support) */
input { caret-color: red; }

/* control text selection by the user */
.no-select { user-select: none; }        /* disable selection */
.select-all { user-select: all; }        /* select whole element on click */
.select-text { user-select: text; }      /* normal text selection */
.select-contain { user-select: contain; } /* selection stays within */

/* email addresses, code blocks often user-select: all */

appearance и стилизация форм

appearance: none снимает с контролов нативное оформление ОС, позволяя стилизовать их целиком через CSS — необходимо для единообразного межбраузерного дизайна форм. После удаления стрелки select добавьте свою background-image. Кастомные чекбоксы — appearance: none плюс :checked для состояния. Для полной поддержки добавляйте префиксы -webkit-/-moz-. Тестируйте тщательно: некоторые контролы (date, color) трудно перекрасить полностью.

css3
/* remove native widget styling */
input, select, button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

/* custom select arrow (after removing native) */
select {
  background-image: url("arrow.svg");
  background-repeat: no-repeat;
  background-position: right 10px center;
  padding-right: 30px;
}

/* style checkbox/radio with appearance: none */
input[type="checkbox"] {
  appearance: none;
  width: 20px; height: 20px;
  border: 2px solid #999;
  border-radius: 4px;
}
input[type="checkbox"]:checked {
  background: var(--primary);
  border-color: var(--primary);
}

scroll-behavior и полоса прокрутки

scroll-behavior: smooth на <html> делает переходы по якорям плавными вместо прыжка — в паре с prefers-reduced-motion отключайте для чувствительных пользователей. Кастомные скроллбары: стандартные свойства scrollbar-width/scrollbar-color работают в Firefox и современном Chrome; псевдоэлементы ::-webkit-scrollbar дают более тонкий контроль в WebKit/Blink. Деликатные скроллбары доводят UX прокручиваемых областей.

css3
/* smooth scrolling for anchor links */
html { scroll-behavior: smooth; }

/* respect reduced motion */
@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
}

/* custom scrollbar (WebKit) */
.scroll-area::-webkit-scrollbar { width: 8px; }
.scroll-area::-webkit-scrollbar-track { background: #f1f1f1; }
.scroll-area::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; }
.scroll-area::-webkit-scrollbar-thumb:hover { background: #555; }

/* standard scrollbar-color (Firefox + spec) */
.scroll-area {
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}
20

Продвинутые и современные возможности

Scroll Snap

Scroll Snap создаёт карусельную или постраничную прокрутку без JavaScript. scroll-snap-type: x/y + mandatory/proximity задаёт ось и строгость. Дети с scroll-snap-align прилипают к start/center/end. mandatory принуждает прилипание (хорошо для полноэкранных секций); proximity прилипает только вблизи (мягче, для галерей). Сочетайте со scroll-margin для смещения точек прилипания ниже прилипающих шапок.

css3
.gallery {
  scroll-snap-type: x mandatory;  /* snap horizontally, must snap */
  overflow-x: auto;
  display: flex;
}

.gallery > img {
  scroll-snap-align: center;   /* start | center | end */
  scroll-snap-stop: always;    /* can't skip snaps */
  flex: 0 0 80%;
}

/* vertical full-page snap */
.pages {
  scroll-snap-type: y mandatory;
  height: 100vh;
  overflow-y: scroll;
}
.page { scroll-snap-align: start; height: 100vh; }

/* proximity: only snaps when close (gentler) */
.soft { scroll-snap-type: y proximity; }

object-fit и object-position

object-fit управляет тем, как <img> или <video> заполняют свой блок — медиа-аналог background-size. cover заполняет блок и обрезает излишек; contain вмещает всё медиа с возможными пустотами; fill растягивает (искажая). object-position задаёт фокусную точку — полезно, когда cover обрезает важные части изображения. Это устраняет необходимость хаков с background-image для адаптивных медиа.

css3
/* cover: fill box, crop overflow (like background-size: cover) */
.avatar img {
  width: 100px; height: 100px;
  object-fit: cover;        /* cover | contain | fill | none | scale-down */
  object-position: center;  /* position the focal point */
  border-radius: 50%;
}

/* contain: whole image visible, may letterbox */
.preview img {
  width: 300px; height: 200px;
  object-fit: contain;
  background: #eee;
}

/* object-position shifts the visible area */
.banner img {
  width: 100%; height: 300px;
  object-fit: cover;
  object-position: top;  /* show top of image */
}

will-change

will-change подсказывает браузеру, что свойство скоро изменится, позволяя заранее выделить GPU-слои и оптимизировать. Применяйте прямо перед анимацией и снимайте после — постоянное использование на многих элементах расходует память и может навредить. Перечисляйте только реально анимируемые свойства (transform, opacity, filter). Злоупотребление даёт эффект, противоположный ожидаемому, — применяйте умеренно и осознанно.

css3
/* hint that an element will animate transform */
.card { will-change: transform; }

/* remove when not needed (frees GPU memory) */
.card.idle { will-change: auto; }

/* multiple properties */
.complex { will-change: transform, opacity; }

/* AVOID: permanent will-change on many elements */
/* .all { will-change: transform, opacity, top, left; } */ /* bad */

/* apply just before animation, remove after */
.prepare { will-change: transform; }
/* JS: el.classList.add('prepare'); 
   setTimeout(() => el.classList.remove('prepare'), 1000); */

contain

contain сообщает браузеру, что элемент независим от остальной страницы, включая крупные оптимизации — изменения внутри contained-элемента не вызывают пересчёт вовне. layout, paint, style и size — типы изоляции. strict (все четыре, включая size) самый сильный. Применяйте contain к повторяющимся виджетам, пунктам списков или рекламе, ограничивая стоимость reflow/repaint. size требует явных размеров.

css3
/* isolate an element's layout/paint/style from the rest */
.widget {
  contain: layout paint style;  /* or: strict, content */
  
  /* size: the element's size is independent of its children */
  contain: size;  /* needs explicit dimensions */
}

/* layout: changes inside don't affect outside layout */
/* paint: children don't render outside the box (clipped) */
/* style: counters and quotes are scoped */
/* size: element ignores children for sizing */

/* full isolation */
.isolated { contain: strict; } /* = size layout paint style */
.content-isolated { contain: content; } /* = layout paint style */

/* useful for performance on complex widgets, lists, ads */

aspect-ratio и универсальный gap

aspect-ratio поддерживает соотношение width:height на любом элементе, предотвращая сдвиг раскладки при загрузке медиа. gap (и его полные формы row-gap/column-gap) — современный инструмент интервалов, работающий во flexbox, grid и multicolumn — устраняя хаки .item + margin + :last-child. Обе возможности поддерживаются всеми современными браузерами и вместе решают две самые частые боли CSS: удержание пропорций медиа и аккуратные интервалы между элементами.

css3
/* aspect-ratio works on any element */
.video-wrap {
  aspect-ratio: 16 / 9;
  background: black;
}

/* gap works in flex, grid, and multi-column */
.flex { display: flex; gap: 16px; }
.grid { display: grid; gap: 16px; }
.cols { column-count: 3; column-gap: 16px; }

/* row-gap / column-gap longhands */
.layout {
  display: grid;
  row-gap: 24px;
  column-gap: 16px;
}

/* gap replaced margin-based spacing hacks */
/* (no more .item:last-child { margin-right: 0 }) */

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.