Spec-Zone.ru › CSS

CSS-свойство `background`

Базовая поддержка Широко доступно

Эта функция хорошо зарекомендовала себя и работает на многих устройствах и в различных версиях браузеров. Она доступна во всех браузерах с июля 2015 года.

Сокращённое свойство background CSS задаёт сразу все свойства стилей фона, такие как цвет, изображение, область начала, размер и способ повтора.

Попробуйте

background: green;
background: content-box radial-gradient(crimson, skyblue);
background: no-repeat url("/shared-assets/images/examples/lizard.png");
background: left 5% / 15% 60% repeat-x
  url("/shared-assets/images/examples/star.png");
background:
  center / contain no-repeat
    url("/shared-assets/images/examples/firefox-logo.svg"),
  #eeeeee 35% url("/shared-assets/images/examples/lizard.png");
<section id="default-example">
  <div id="example-element"></div>
</section>
#example-element {
  min-width: 100%;
  min-height: 100%;
  padding: 10%;
}

Составные свойства

Это свойство является сокращённой записью следующих свойств CSS:

  • background-attachment
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-repeat
  • background-size

Синтаксис

/* Using a <background-color> */
background: green;

/* Using a <bg-image> and <repeat-style> */
background: url("test.jpg") repeat-y;

/* Using a <visual-box> and <'background-color'> */
background: border-box red;

/* A single image, centered and scaled */
background: no-repeat center/80% url("../img/image.png");

/* Global values */
background: inherit;
background: initial;
background: revert;
background: revert-layer;
background: unset;

Значения

<attachment>
См. background-attachment. По умолчанию: scroll.
<visual-box>
См. background-clip и background-origin. По умолчанию: соответственно border-box и padding-box.
<'background-color'>
См. background-color. По умолчанию: transparent.
<bg-image>
См. background-image. По умолчанию: none.
<bg-position>
См. background-position. По умолчанию: 0% 0%.
<repeat-style>
См. background-repeat. По умолчанию: repeat.
<bg-size>
См. background-size. По умолчанию: auto.

Описание

Сокращённое свойство background позволяет задать все свойства фона CSS в одном объявлении. Фон располагается под содержимым элемента. Если заданы несколько значений фона, разделённых запятыми, каждое из них образует слой фона, который отрисовывается поверх предыдущих слоёв.

Свойство background задаётся одним или несколькими слоями фона, разделёнными запятыми. Каждый слой может включать ноль, один или два компонента <visual-box> и ноль или один компонент <attachment>, <bg-image>, <bg-position>, <bg-size> и <repeat-style>. Если заданы два компонента <bg-position>, <bg-size> или <repeat-style>, первое значение задаёт горизонтальную величину, а второе — вертикальную. Если указано только одно значение, оно применяется к обоим измерениям.

Компонент <'background-color'> может быть указан только в последнем заданном слое фона.

Для свойств компонентов, не заданных в значении сокращённого свойства background, используются значения по умолчанию.

Порядок свойств компонентов

Поскольку некоторые свойства компонентов используют одинаковые типы значений, их порядок в сокращённой записи имеет значение.

Значение <bg-size> можно указать только сразу после <bg-position>, отделив его символом /. Например: 10px 10px / 80% 80% означает, что изображение фона имеет высоту и ширину 80% от размеров элемента и располагается на расстоянии 10px от верхнего края и 10px от левого края верхнего левого угла элемента. Внутри <bg-position>, если оба значения являются длинами или одно является длиной, а другое — center, первое значение задаёт горизонтальное положение, а второе — вертикальное.

Каждый слой фона может включать ноль, одно или два значения <visual-box>. Если указано только одно значение, оно задаёт и background-origin, и background-clip. Если указаны два значения, первое задаёт значение background-origin, а второе — значение background-clip. Если значения <visual-box> не указаны, для background-origin используется значение по умолчанию padding-box, а для background-clip — border-box.

Для остальных свойств фона порядок не задан, однако для единообразия и удобства чтения рекомендуется следующий порядок; помните, что ни одно из значений не является обязательным:

<bg-image> <bg-position> / <bg-size> <repeat-style> <attachment> <bg-clip> <bg-origin> <'background-color'>

В следующем объявлении background явно задаются все значения по умолчанию в этом порядке:

background: none 0% 0% / auto auto repeat scroll border-box padding-box
  transparent;

Следующие три строки CSS эквивалентны приведённому выше объявлению, несмотря на различие в порядке:

background: none;
background: transparent;
background: repeat scroll 0% 0% / auto padding-box border-box none transparent;

Порядок отрисовки изображений

Если указано несколько фонов, разделённых запятыми, они образуют несколько слоёв фона, расположенных друг над другом. Первый фон в списке создаёт верхний слой. Если верхний слой не содержит прозрачных областей, виден будет только он.

Последний слой является нижним. Цвет фона всегда задаётся в этом слое.

Применение фона body ко всему документу

Если вычисленное значение background-image элемента документа <html> :root равно none, а его background-color — transparent, браузер перенесёт стили background, заданные для элемента <body>, на :root и будет считать, что для <body> задано значение background: initial. Иными словами, элемент <html> получает все стили background, заданные для элемента <body>, а свойства фона элемента <body> устанавливаются в исходные значения.

В связи с таким поведением авторы спецификации рекомендуют задавать стили фона документа в блоке стилей body, а не html. Однако важно учитывать, что использование изоляции отключает это поведение. Если для свойства contain задано любое значение, кроме none, для элемента <html> или <body>, свойство background и его длинные формы не наследуются элементом <html> от элемента <body>.

Формальное определение

Начальное значение как у каждого из свойств сокращённой записи:
  • background-image
  • background-position
  • background-size
  • background-repeat
  • background-origin
  • background-clip
  • background-attachment
  • background-color
Применяется к всем элементам
Наследуется нет
Проценты как у каждого из свойств сокращённой записи:
  • background-position
  • background-size
Вычисленное значение как у каждого из свойств сокращённой записи:
  • background-image
  • background-position
  • background-size
  • background-repeat
  • background-origin
  • background-clip
  • background-attachment
  • background-color
Тип анимации как у каждого из свойств сокращённой записи:
  • background-color
  • background-image
  • background-clip
  • background-position
  • background-size
  • background-repeat
  • background-attachment

Формальный синтаксис

background = 
  <bg-layer>#? , <final-bg-layer>

<bg-layer> = 
  <bg-image> ||
  <bg-position> [ / <bg-size> ]? ||
  <repeat-style> ||
  <attachment> ||
  <visual-box> ||
  <visual-box>

<final-bg-layer> = 
  <bg-image> ||
  <bg-position> [ / <bg-size> ]? ||
  <repeat-style> ||
  <attachment> ||
  <visual-box> ||
  <visual-box> ||
  <'background-color'>

<bg-image> = 
  <image> |
  none

<bg-position> = 
  [ [ left | center | right | top | bottom | <length-percentage> ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ] | [ center | [ left | right ] <length-percentage>? ] && [ center | [ top | bottom ] <length-percentage>? ] ]

<bg-size> = 
  [ <length-percentage [0,∞]> | auto ]{1,2} |
  cover |
  contain

<repeat-style> = 
  repeat-x |
  repeat-y |
  [ repeat | space | round | no-repeat ]{1,2}

<attachment> = 
  scroll |
  fixed |
  local

<visual-box> = 
  content-box |
  padding-box |
  border-box

<image> = 
  <url> |
  <image()> |
  <image-set()> |
  <element()> |
  <paint()> |
  <cross-fade()> |
  <gradient>

<length-percentage> = 
  <length> |
  <percentage>

<image()> = 
  image( <image-tags>? [ <image-src>? , <color>? ]! )

<image-set()> = 
  image-set( <image-set-option># )

<element()> = 
  element( <id-selector> )

<paint()> = 
  paint( <ident>, <declaration-value>? )

<cross-fade()> = 
  cross-fade( <cf-mixing-image> , <cf-final-image>? )

<gradient> = 
  <linear-gradient()> |
  <repeating-linear-gradient()> |
  <radial-gradient()> |
  <repeating-radial-gradient()> |
  <conic-gradient()> |
  <repeating-conic-gradient()>

<image-tags> = 
  ltr |
  rtl

<image-src> = 
  <url> |
  <string>

<color> = 
  <color-base> |
  currentColor |
  <system-color> |
  <light-dark()> |
  <deprecated-system-color>

<image-set-option> = 
  [ <image> | <string> ] [ <resolution> || type(<string>) ]

<id-selector> = 
  <hash-token>

<cf-mixing-image> = 
  <percentage>? &&
  <image>

<cf-final-image> = 
  <image> |
  <color>

<linear-gradient()> = 
  linear-gradient( [ <linear-gradient-syntax> ] )

<repeating-linear-gradient()> = 
  repeating-linear-gradient( [ <linear-gradient-syntax> ] )

<radial-gradient()> = 
  radial-gradient( [ <radial-gradient-syntax> ] )

<repeating-radial-gradient()> = 
  repeating-radial-gradient( [ <radial-gradient-syntax> ] )

<conic-gradient()> = 
  conic-gradient( [ <conic-gradient-syntax> ] )

<repeating-conic-gradient()> = 
  repeating-conic-gradient( [ <conic-gradient-syntax> ] )

<color-base> = 
  <hex-color> |
  <color-function> |
  <named-color> |
  <color-mix()> |
  transparent

<system-color> = 
  AccentColor |
  AccentColorText |
  ActiveText |
  ButtonBorder |
  ButtonFace |
  ButtonText |
  Canvas |
  CanvasText |
  Field |
  FieldText |
  GrayText |
  Highlight |
  HighlightText |
  LinkText |
  Mark |
  MarkText |
  SelectedItem |
  SelectedItemText |
  VisitedText

<light-dark()> = 
  light-dark( <color>, <color> )

<deprecated-system-color> = 
  ActiveBorder |
  ActiveCaption |
  AppWorkspace |
  Background |
  ButtonHighlight |
  ButtonShadow |
  CaptionText |
  InactiveBorder |
  InactiveCaption |
  InactiveCaptionText |
  InfoBackground |
  InfoText |
  Menu |
  MenuText |
  Scrollbar |
  ThreeDDarkShadow |
  ThreeDFace |
  ThreeDHighlight |
  ThreeDLightShadow |
  ThreeDShadow |
  Window |
  WindowFrame |
  WindowText

<linear-gradient-syntax> = 
  [ [ <angle> | <zero> | to <side-or-corner> ] || <color-interpolation-method> ]? , <color-stop-list>

<radial-gradient-syntax> = 
  [ [ [ <radial-shape> || <radial-size> ]? [ at <position> ]? ] || <color-interpolation-method> ]? , <color-stop-list>

<conic-gradient-syntax> = 
  [ [ [ from [ <angle> | <zero> ] ]? [ at <position> ]? ] || <color-interpolation-method> ]? , <angular-color-stop-list>

<color-function> = 
  <rgb()> |
  <rgba()> |
  <hsl()> |
  <hsla()> |
  <hwb()> |
  <lab()> |
  <lch()> |
  <oklab()> |
  <oklch()> |
  <color()>

<named-color> = 
  aliceblue |
  antiquewhite |
  aqua |
  aquamarine |
  azure |
  beige |
  bisque |
  black |
  blanchedalmond |
  blue |
  blueviolet |
  brown |
  burlywood |
  cadetblue |
  chartreuse |
  chocolate |
  coral |
  cornflowerblue |
  cornsilk |
  crimson |
  cyan |
  darkblue |
  darkcyan |
  darkgoldenrod |
  darkgray |
  darkgreen |
  darkgrey |
  darkkhaki |
  darkmagenta |
  darkolivegreen |
  darkorange |
  darkorchid |
  darkred |
  darksalmon |
  darkseagreen |
  darkslateblue |
  darkslategray |
  darkslategrey |
  darkturquoise |
  darkviolet |
  deeppink |
  deepskyblue |
  dimgray |
  dimgrey |
  dodgerblue |
  firebrick |
  floralwhite |
  forestgreen |
  fuchsia |
  gainsboro |
  ghostwhite |
  gold |
  goldenrod |
  gray |
  green |
  greenyellow |
  grey |
  honeydew |
  hotpink |
  indianred |
  indigo |
  ivory |
  khaki |
  lavender |
  lavenderblush |
  lawngreen |
  lemonchiffon |
  lightblue |
  lightcoral |
  lightcyan |
  lightgoldenrodyellow |
  lightgray |
  lightgreen |
  lightgrey |
  lightpink |
  lightsalmon |
  lightseagreen |
  lightskyblue |
  lightslategray |
  lightslategrey |
  lightsteelblue |
  lightyellow |
  lime |
  limegreen |
  linen |
  magenta |
  maroon |
  mediumaquamarine |
  mediumblue |
  mediumorchid |
  mediumpurple |
  mediumseagreen |
  mediumslateblue |
  mediumspringgreen |
  mediumturquoise |
  mediumvioletred |
  midnightblue |
  mintcream |
  mistyrose |
  moccasin |
  navajowhite |
  navy |
  oldlace |
  olive |
  olivedrab |
  orange |
  orangered |
  orchid |
  palegoldenrod |
  palegreen |
  paleturquoise |
  palevioletred |
  papayawhip |
  peachpuff |
  peru |
  pink |
  plum |
  powderblue |
  purple |
  rebeccapurple |
  red |
  rosybrown |
  royalblue |
  saddlebrown |
  salmon |
  sandybrown |
  seagreen |
  seashell |
  sienna |
  silver |
  skyblue |
  slateblue |
  slategray |
  slategrey |
  snow |
  springgreen |
  steelblue |
  tan |
  teal |
  thistle |
  tomato |
  turquoise |
  violet |
  wheat |
  white |
  whitesmoke |
  yellow |
  yellowgreen

<color-mix()> = 
  color-mix( <color-interpolation-method> , [ <color> && <percentage [0,100]>? ]#{2})

<side-or-corner> = 
  [ left | right ] ||
  [ top | bottom ]

<color-interpolation-method> = 
  in [ <rectangular-color-space> | <polar-color-space> <hue-interpolation-method>? | <custom-color-space> ]

<color-stop-list> = 
  <linear-color-stop> , [ <linear-color-hint>? , <linear-color-stop> ]#?

<radial-shape> = 
  circle |
  ellipse

<radial-size> = 
  <radial-extent> |
  <length [0,∞]> |
  <length-percentage [0,∞]>{2}

<position> = 
  [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]

<angular-color-stop-list> = 
  <angular-color-stop> , [ <angular-color-hint>? , <angular-color-stop> ]#?

<rgb()> = 
  rgb( <percentage>#{3} , <alpha-value>? ) |
  rgb( <number>#{3} , <alpha-value>? ) |
  rgb( [ <number> | <percentage> | none ]{3} [ / [ <alpha-value> | none ] ]? )

<rgba()> = 
  rgba( <percentage>#{3} , <alpha-value>? ) |
  rgba( <number>#{3} , <alpha-value>? ) |
  rgba( [ <number> | <percentage> | none ]{3} [ / [ <alpha-value> | none ] ]? )

<hsl()> = 
  hsl( <hue>, <percentage>, <percentage>, <alpha-value>? ) |
  hsl( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<hsla()> = 
  hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ) |
  hsla( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<hwb()> = 
  hwb( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<lab()> = 
  lab( [<percentage> | <number> | none] [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ / [<alpha-value> | none] ]? )

<lch()> = 
  lch( [<percentage> | <number> | none] [ <percentage> | <number> | none] [ <hue> | none] [ / [<alpha-value> | none] ]? )

<oklab()> = 
  oklab( [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ / [<alpha-value> | none] ]? )

<oklch()> = 
  oklch( [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ <hue> | none] [ / [<alpha-value> | none] ]? )

<color()> = 
  color( [ from <color> ]? <colorspace-params> [ / [ <alpha-value> | none ] ]? )

<rectangular-color-space> = 
  srgb |
  srgb-linear |
  display-p3 |
  display-p3-linear |
  a98-rgb |
  prophoto-rgb |
  rec2020 |
  lab |
  oklab |
  xyz |
  xyz-d50 |
  xyz-d65

<polar-color-space> = 
  hsl |
  hwb |
  lch |
  oklch

<hue-interpolation-method> = 
  [ shorter | longer | increasing | decreasing ] hue

<custom-color-space> = 
  <dashed-ident>

<linear-color-stop> = 
  <color> <color-stop-length>?

<linear-color-hint> = 
  <length-percentage>

<radial-extent> = 
  closest-corner |
  closest-side |
  farthest-corner |
  farthest-side

<angular-color-stop> = 
  <color> <color-stop-angle>?

<angular-color-hint> = 
  <angle-percentage> |
  <zero>

<alpha-value> = 
  <number> |
  <percentage>

<hue> = 
  <number> |
  <angle>

<colorspace-params> = 
  [<custom-params> | <predefined-rgb-params> | <xyz-params>]

<color-stop-length> = 
  <length-percentage>{1,2}

<color-stop-angle> = 
  [ <angle-percentage> | <zero> ]{1,2}

<angle-percentage> = 
  <angle> |
  <percentage>

<custom-params> = 
  <dashed-ident> [ <number> | <percentage> | none ]+

<predefined-rgb-params> = 
  <predefined-rgb> [ <number> | <percentage> | none ]{3}

<xyz-params> = 
  <xyz> [ <number> | <percentage> | none ]{3}

Доступность

Браузеры не предоставляют вспомогательным технологиям специальных сведений об изображениях фона. Это особенно важно для программ чтения с экрана: они не сообщают о наличии такого изображения и, следовательно, не передают пользователям никакой информации о нём. Если изображение содержит сведения, критически важные для понимания общего назначения страницы, лучше описать его семантически в документе.

  • MDN: разъяснения к руководству 1.1 WCAG
  • [Понимание критерия успеха 1.1.1 W3C: понимание WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/text-equiv-all.html)

Примеры

Задание фона с помощью ключевых слов цвета и изображений

HTML

<p class="top-banner">
  Starry sky<br />
  Twinkle twinkle<br />
  Starry sky
</p>
<p class="warning">Here is a paragraph</p>
<p></p>

CSS

.warning {
  background: pink;
}

.top-banner {
  background: url("star-solid.gif") #9999ff repeat-y fixed;
}

Результат

Спецификации

Спецификация
Модуль фонов и рамок CSS, уровень 3
# background

Совместимость с браузерами

Компьютер Мобильные устройства
Chrome Edge Firefox Opera Safari Chrome для Android Firefox для Android Opera для Android Safari в iOS Samsung Internet Android WebView WebView в iOS
background
1
12
1
3.5
1
18
4
10.1
1
1.0
2
1
SVG_image_as_background
1
12
4
9.5
3.1
18
4
10.1
1
1.0
4.4
1
background-clip
21
12
22
15
5.1
25
22
14
4
1.5
3
4
background-origin
21
12
22
15
5.1
25
22
14
4
1.5
3
4
background-size
21
12
9
21
5.1
25
18
14
4
1.5
3
4
border-area
150
150
Нет
134
18.2
150
Нет
101
18.2
Нет
150
18.2
border-box
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
bottom
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
center
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
content-box
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
currentColor
1
12
1.5
9.5
4
18
4
14
3.2
1.0
37
3.2
fixed
≤15
≤15
≤50
15
≤9.1
18
≤50
14
≤9.3
1.0
4.4
≤9.3
left
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
local
1
12
1
15
1
18
4
14
1
1.0
4.4
1
multiple_backgrounds
1
12
3.6
10.5
1.3
18
4
14
1
1.0
2
1
no-repeat
1
12
1
15
1
18
4
14
1
1.0
4.4
1
none
1
12
1
15
1
18
4
14
1
1.0
4.4
1
padding-box
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
repeat
1
12
1
15
1
18
4
14
1
1.0
4.4
1
repeat-x
1
12
1
15
1
18
4
14
1
1.0
4.4
1
repeat-y
1
12
1
15
1
18
4
14
1
1.0
4.4
1
right
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
round
1
12
1
15
1
18
4
14
1
1.0
4.4
1
scroll
1
12
1
15
1
18
4
14
1
1.0
4.4
1
space
1
12
1
15
1
18
4
14
1
1.0
4.4
1
top
≤31
≤15
≤50
≤18
≤9.1
≤31
≤50
≤18
≤9.3
≤2.0
≤4.4.3
≤9.3
transparent
1
12
1
15
1
18
4
14
1
1.0
4.4
1
x-end
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
x-start
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
y-end
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
y-start
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26

См. также

  • box-decoration-break
  • Использование градиентов
  • Использование нескольких фонов

© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/background

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API