- 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
- Как сделать картинку фоном в HTML и CSS. 3 простых способа
- Способ 1
- Способ 2
- Способ 3
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.Как сделать картинку фоном в HTML и CSS. 3 простых способа
Приветствую. В этой статье я хочу рассказать о трех способах размещения изображения в качестве фона всей страницы при помощи только HTML + CSS (без использования JS).
Итак, требования к фоновому изображению у нас следующие:
- Покрывается 100% ширины и высоты страницы
- Фон масштабируется при необходимости (background растягивается или сжимается в зависимости от размеров экрана)
- Сохраняются пропорции картинки (aspect ratio)
- Изображение центрировано на странице
- Фон не вызывает скроллов
- Решение максимально кроссбраузерное
- Не используются никакие другие технологии кроме CSS
Способ 1
На мой взгляд, это лучший способ, ведь он самый простой, лаконичный и современный. Он использует свойство CSS3 background-size , которое мы применяем к тегу html . Именно html , а не body , т.к. его высота больше или равна высоте окна браузера.
Устанавливаем фиксированный и центрированный фон, затем корректируем его размер, используя background-size: cover .
Chrome (любая версия) Opera 10+ Firefox 3.6+ Safari 3+ IE 9+
Для того чтобы изображения загружались быстро, размещайте свои сайты только у проверенных хостинг-провайдеров, например, Beget.com Пользователи и поисковые системы любят быстрые сайты.
Способ 2
Этот способ предусматривает использование элемента img, размер которого будет изменяться в зависимости от размера окна браузера. Чтобы растянуть изображение на весь экран, ему необходимо задать min-height и width со значением 100%. А чтобы изображение не сжималось до размера меньшего, чем оригинальный, установим min-width со значением равным ширине картинки.
В случае если ширина окна будет меньше ширины изображения, будет использоваться media query для выравнивания бэкграунда по центру.
Способ 3
Еще один способ заключается в следующем: фиксируем изображение к левому верхнему углу страницы и растягиваем его при помощи свойств min-width и min-height 100%, сохраняя при этом соотношение сторон.
Правда при таком подходе картинка не центрируется. Но эта проблема решается заворачиванием картинки в , который мы делаем в 2 раза больше размера окна. А само изображение мы растягиваем и помещаем по центру.
Этот способ работает в хороших браузерах и IE 8+.
Надеюсь, эта информация будет для Вас полезной. Лично я частенько пользуюсь этими методами, особенно первым. Наверняка есть и другие способы поместить изображение на задний фон при помощи CSS. Если Вы о них знаете, поделитесь, пожалуйста, комментариях.