- 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
- CSS background-repeat Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- Example
- Example
- background-repeat
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Как добавить изображение фоном. Свойство background-image
- Значения
- Повторное изображение
- Размер изображения
- Наследование
- Примеры использования
- Нюансы использования
- Материалы по теме
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.CSS background-repeat Property
The background-repeat property sets if/how a background image will be repeated.
By default, a background-image is repeated both vertically and horizontally.
Tip: The background image is placed according to the background-position property. If no background-position is specified, the image is always placed at the element’s top left corner.
Default value: repeat Inherited: no Animatable: no. Read about animatable Version: CSS1 JavaScript syntax: object.style.backgroundRepeat=»repeat-x» Try it Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value Description Demo repeat The background image is repeated both vertically and horizontally. The last image will be clipped if it does not fit. This is default Demo ❯ repeat-x The background image is repeated only horizontally Demo ❯ repeat-y The background image is repeated only vertically Demo ❯ no-repeat The background-image is not repeated. The image will only be shown once Demo ❯ space The background-image is repeated as much as possible without clipping. The first and last image is pinned to either side of the element, and whitespace is distributed evenly between the images Demo ❯ round The background-image is repeated and squished or stretched to fill the space (no gaps) Demo ❯ initial Sets this property to its default value. Read about initial inherit Inherits this property from its parent element. Read about inherit More Examples
Example
Repeat a background image both vertically and horizontally (this is default):
Example
Repeat a background image only horizontally:
Example
Do not repeat a background image. The image will only be shown once:
Example
Using background-repeat: space and background-repeat: round:
#example2 <
border: 2px solid black;
padding: 25px;
background: url(«w3css.gif»);
background-repeat: space;
>#example3 border: 1px solid black;
padding: 25px;
background: url(«w3css.gif»);
background-repeat: round;
>Example
Use different background properties to create a «hero» image:
.hero-image <
background-image: url(«photographer.jpg»); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
>background-repeat
The background-repeat CSS property sets how background images are repeated. A background image can be repeated along the horizontal and vertical axes, or not repeated at all.
Try it
By default, the repeated images are clipped to the size of the element, but they can be scaled to fit (using round ) or evenly distributed from end to end (using space ).
Syntax
/* Keyword values */ background-repeat: repeat-x; background-repeat: repeat-y; background-repeat: repeat; background-repeat: space; background-repeat: round; background-repeat: no-repeat; /* Two-value syntax: horizontal | vertical */ background-repeat: repeat space; background-repeat: repeat repeat; background-repeat: round space; background-repeat: no-repeat round; /* Global values */ background-repeat: inherit; background-repeat: initial; background-repeat: revert; background-repeat: revert-layer; background-repeat: unset;
Values
The one-value syntax is a shorthand for the full two-value syntax:
Single value Two-value equivalent repeat-x repeat no-repeat repeat-y no-repeat repeat repeat repeat repeat space space space round round round no-repeat no-repeat no-repeat In the two-value syntax, the first value represents the horizontal repetition behavior and the second value represents the vertical behavior. Here is an explanation of how each option works for either direction:
repeat The image is repeated as much as needed to cover the whole background image painting area. The last image will be clipped if it doesn’t fit. space The image is repeated as much as possible without clipping. The first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images. The background-position property is ignored unless only one image can be displayed without clipping. The only case where clipping happens using space is when there isn’t enough room to display one image. round As the allowed space increases in size, the repeated images will stretch (leaving no gaps) until there is room (space left >= half of the image width) for another one to be added. When the next image is added, all of the current ones compress to allow room. Example: An image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added. They will then compress to 225px. no-repeat The image is not repeated (and hence the background image painting area will not necessarily be entirely covered). The position of the non-repeated background image is defined by the background-position CSS property. Formal definition
Initial value repeat Applies to all elements. It also applies to ::first-letter and ::first-line . Inherited no Computed value a list, each item consisting of two keywords, one per dimension Animation type discrete Formal syntax
background-repeat =
#=
repeat-x |
repeat-y |
[ repeat | space | round | no-repeat ]Как добавить изображение фоном. Свойство background-image
background-image позволяет добавить изображение в качестве фона для выбранного элемента. Фоновое изображение может быть любого типа и повторяться или масштабироваться в зависимости от настроек.
Значения
- url(‘путь_к_изображению’) — указывает путь к изображению. Вы можете указать относительный путь к изображению на вашем сервере или абсолютный URL для изображения в интернете.
- none — значение по умолчанию, где нет фона. Если не хотите использовать изображение в качестве фона, вы можете установить background-image: none; .
- linear-gradient() , radial-gradient() , repeating-linear-gradient() , repeating-radial-gradient() — создают градиент фона без использования изображений. Можно определить цветовую палитру и ориентацию градиента.
Повторное изображение
background-repeat: repeat; — значение по умолчанию, изображение повторяется по горизонтали и вертикали. Изображение будет заполнять фон элемента, повторяясь при необходимости.
background-repeat: repeat-x; — повторяется только по горизонтали.
background-repeat: repeat-y; — повторяется только по вертикали.
background-repeat: no-repeat; — отображается только один раз без повторения.
Размер изображения
background-size: auto; — отображается в своём естественном размере.
background-size: cover; — масштабируется так, чтобы полностью заполнить фон элемента, возможно, обрезая его.
background-size: contain; — масштабируется так, чтобы полностью поместиться в фон элемента без искажений. Белые полосы могут появиться по краям фона, если пропорции изображения и фона не совпадают.
Наследование
Свойство background-image не наследуется дочерними элементами. Каждый элемент должен самостоятельно задавать фоновое изображение.
Примеры использования
Добавление изображения на фон определённого элемента
Добавление повторяющегося изображения на фон элемента
Добавление градиента на фон
Нюансы использования
- Фоновые картинки не будут автоматически масштабироваться под размеры родительского элемента. Если размеры картинки и родительского элемента не совпадают, то картинка обрежется или начнёт повторяться.
- Если задать цвет фона и background-image для одного элемента, то картинка будет отображаться поверх цвета фона.
⭐ Поддержка браузерами свойства background-image
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.