- background-image
- Синтаксис
- Значения
- Официальный синтаксис
- Примеры
- Несколько фонов и прозрачность
- HTML содержимое
- CSS содержимое
- Спецификации
- Совместимость браузеров
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- background
- Кратко
- Пример
- Как пишется
- Подсказки
- background
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- background
- Try it
- Constituent properties
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Setting backgrounds with color keywords and images
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
background-image
Свойство CSS background-image устанавливает одно или несколько фоновых изображений для элемента. Изображения рисуются в слоях контекстов наложения одно поверх другого. Первый слой выводится так, чтобы он был ближе всего к пользователю.
Границы border элемента затем рисуются поверх них, и background-color рисуется под ними. То, как изображения отрисовываются относительно рамки и её границ, определяется CSS-свойствами background-clip и background-origin .
Если указанное изображение не может быть нарисовано (например, когда файл, определённый указанным URI, не может быть загружен), браузеры обрабатывают его так, как если бы оно было значением none .
Примечание: Даже, если изображение непрозрачно и цвет не будет показан при нормальных обстоятельствах, веб-разработчику следует всегда указывать атрибут background-color . Если изображение не может быть загружено —например, в случае отказа сетевого подключения — у элемента будет отображён цветной фон.
Начальное значение | none |
---|---|
Применяется к | все элементы. Это также применяется к ::first-letter и ::first-line . |
Наследуется | нет |
Обработка значения | как указано, но с абсолютными значениями url |
Animation type | discrete |
Синтаксис
background-image: none; background-image: url(http://www.example.com/bck.png); background-image: inherit;
Значения
Это ключевое слово обозначает отсутствие изображений.
(en-US) обозначает изображение для отображения. Их может быть несколько, разделённых запятыми, поскольку поддерживаетсянесколько фонов (en-US) .
Официальный синтаксис
background-image =
# (en-US)
=
| (en-US)
none
=
| (en-US)
(en-US)
=
url( (en-US) * (en-US) ) | (en-US)
src( (en-US) * (en-US) )
Примеры
Несколько фонов и прозрачность
Обратите внимание, что изображение звезды частично прозрачно и наложено на изображение кошки.
HTML содержимое
div> p class="catsandstars"> This paragraph is full of catsbr />and stars. p> p>This paragraph is not.p> p class="catsandstars"> Here are more cats for you.br />Look at them! p> p>And no more.p> div>
CSS содержимое
pre, p font-size: 1.5em; color: #FE7F88; background-color: transparent; > div background-image: url("mdn_logo_only_color.png"); > p background-image: none; > .catsandstars background-image: url("startransparent.gif"), url("catfront.png"); background-color: transparent; >
Спецификации
Совместимость браузеров
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 11 февр. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
background
Короткое свойство, чтобы определить всё, что нужно для фона.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Шорткат, позволяющий задать все свойства фона разом. Объединяет в себе:
Пример
Скопировать ссылку «Пример» Скопировано
Код ниже задаёт чёрную заливку фона, фоновую картинку bkg.png, которая не будет повторяться, будет расположена по центру по вертикали и горизонтали, а также закроет всю площадь родителя.
div background: #000000 url("bkg.png") no-repeat center / cover;>
div background: #000000 url("bkg.png") no-repeat center / cover; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Можно указать одно или несколько значений для разных свойств, разделяя их пробелами. Значения можно писать в любом порядке, браузер сам определит, какое значение к какому свойству относится.
В произвольном порядке записи свойств есть исключение: в паре position / size порядок записи только такой, через слэш. А ещё, если опустить size , то position сработает, но если опустить position , то size не сработает.
div /* Сработает */ background: url("bkg.png") center / cover; /* Сработает */ background: url("bkg.png") center; /* Не сработает */ background: url("bkg.png") cover;>
div /* Сработает */ background: url("bkg.png") center / cover; /* Сработает */ background: url("bkg.png") center; /* Не сработает */ background: url("bkg.png") cover; >
Лучше не полагаться слишком на это поведение и использовать полные записи: background — position и background — size .
Ни одно из значений не является обязательным, поэтому ненужные можно смело опустить.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Как и с любым шорткатом, со свойством background нужно обращаться осторожно. Если потребуется переопределить всего одно из заданных значений, то нужно будет переписать и все остальные.
💡 Если в рамках шортката не задано значение для какого-то из свойств и в коде ниже оно не прописано, то свойству устанавливается значение по умолчанию.
💡 Записанные выше отдельные свойства переопределяются заданным ниже свойством background .
background
Универсальное свойство background позволяет установить одновременно до пяти характеристик фона. Значения могут идти в любом порядке, браузер сам определит, какое из них соответствует нужному свойству. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно. В CSS3 допустимо указывать параметры сразу нескольких фонов, перечисляя их через запятую.
Синтаксис
background: [background-attachment || background-color || background-image || background-position || background-repeat] | inherit
= [background-attachment || background-image || background-position || background-repeat] | inherit
= [background-attachment || background-color || background-image || background-position || background-repeat] | inherit
Если наряду с фоновыми изображениями требуется задать цвет фона элемента, он указывается в последнюю очередь после перечисления.
Значения
Любые комбинации пяти значений, разделяемых между собой пробелом, определяющих стиль фона, в произвольном порядке. Ни одно значение не является обязательным, поэтому неиспользуемые можно опустить. inherit наследует значение у родительского элемента.
XHTML 1.0 CSS2.1 IE Cr Op Sa Fx
Duis te feugifacilisi. Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi. Ut wisi enim ad minim veniam, quis nostrud exerci taion ullamcorper suscipit lobortis nisl ut aliquip ex en commodo consequat. Duis te feugifacilisi per suscipit lobortis nisl ut aliquip ex en commodo consequat.
Результат данного примера показан ниже (рис. 1).
Рис. 1. Вид фона и фонового рисунка в блоке фиксированного размера
HTML5 CSS3 IE Cr Op Sa Fx
Объектная модель
[window.]document.getElementById(» elementID «).style.backgroundБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
background
The background shorthand CSS property sets all background style properties at once, such as color, image, origin and size, or repeat method. Component properties not set in the background shorthand property value declaration are set to their default values.
Try it
Constituent properties
This property is a shorthand for the following CSS properties:
Syntax
/* Using a */ background: green; /* Using a and */ background: url("test.jpg") repeat-y; /* Using a and */ 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;
The background property is specified as one or more background layers, separated by commas.
The syntax of each layer is as follows:
- Each layer may include zero or one occurrences of any of the following values:
- The value may only be included immediately after , separated with the ‘/’ character, like this: » center/80% «.
- The value may be included zero, one, or two times. If included once, it sets both background-origin and background-clip . If it is included twice, the first occurrence sets background-origin , and the second sets background-clip .
- The value may only be included in the last layer specified.
Values
See background-clip and background-origin . Default: border-box and padding-box respectively.
See background-color . Default: transparent .
The following three lines of CSS are equivalent:
background: none; background: transparent; background: repeat scroll 0% 0% / auto padding-box border-box none transparent;
Accessibility concerns
Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page’s overall purpose, it is better to describe it semantically in the document.
Formal definition
- background-image : none
- background-position : 0% 0%
- background-size : auto auto
- background-repeat : repeat
- background-origin : padding-box
- background-clip : border-box
- background-attachment : scroll
- background-color : transparent
- background-position : refer to the size of the background positioning area minus size of background image; size refers to the width for horizontal offsets and to the height for vertical offsets
- background-size : relative to the background positioning area
- background-image : as specified, but with url() values made absolute
- background-position : as each of the properties of the shorthand:
- background-position-x : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
- background-position-y : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
- background-color : a color
- background-image : discrete
- background-clip : a repeatable list of
- background-position : a repeatable list of
- background-size : a repeatable list of
- background-repeat : discrete
- background-attachment : discrete
Formal syntax
background =
[ # , ]?=
||
[ / ]? ||
||
||
||
=
||
||
[ / ]? ||
||
||
||
=
|
none=
[ left | center | right | top | bottom | ] |
[ left | center | right | ] [ top | center | bottom | ] |
[ center | [ left | right ] ? ] && [ center | [ top | bottom ] ? ]=
[ | auto ] |
cover |
contain=
repeat-x |
repeat-y |
[ repeat | space | round | no-repeat ]=
scroll |
fixed |
local=
border-box |
padding-box |
content-box=
|=
|=
url( * ) |
src( * )Examples
Setting backgrounds with color keywords and images
HTML
p class="topbanner"> Starry skybr /> Twinkle twinklebr /> Starry sky p> p class="warning">Here is a paragraphp> p>p>
CSS
.warning background: pink; > .topbanner background: url("starsolid.gif") #99f repeat-y fixed; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 18, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.