- background-repeat
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS по теме
- CSS Background Image Repeat
- Example
- Example
- CSS background-repeat: no-repeat
- Example
- CSS background-position
- Example
- The CSS Background Repeat and Position Properties
- background-repeat
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS по теме
- CSS background-position 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-repeat
Определяет, как будет повторяться фоновое изображение, установленное с помощью свойства background-image. Можно установить повторение рисунка только по горизонтали, по вертикали или в обе стороны. В CSS3 допустимо указывать несколько значений для каждого фона, перечисляя значения через запятую.
Синтаксис
background-repeat: no-repeat | repeat | repeat-x | repeat-y | inherit
= repeat-x | repeat-y | [repeat | space | round | no-repeat]
Допустимо указывать два значения, первое ключевое слово задаёт повторение по горизонтали, второе по вертикали.
Значения
no-repeat Устанавливает одно фоновое изображение в элементе без его повторений, положение которого определяется свойством background-position (по умолчанию в левом верхнем углу). Аналогично no-repeat no-repeat . repeat Фоновое изображение повторяется по горизонтали и вертикали. Аналогично repeat repeat . repeat-x Фоновый рисунок повторяется только по горизонтали. Аналогично repeat no-repeat . repeat-y Фоновый рисунок повторяется только по вертикали. Аналогично no-repeat repeat . inherit Наследует значение родителя. space Изображение повторяется столько раз, чтобы полностью заполнить область; если это не удаётся, между картинками добавляется пустое пространство. round Изображение повторяется так, чтобы в области поместилось целое число рисунков; если это не удаётся сделать, то фоновые рисунки масштабируются.
XHTML 1.0 CSS 2.1 IE Cr Op Sa Fx
Даже опытному верстальщику приходится иногда смотреть свой код на наличие опечаток и ошибок. Так что не брезгуй проверять код валидатором, это поможет избежать множества ляпов в будущем.
Результат данного примера показан на рис. 1.
Рис. 1. Повторение фона по горизонтали
Сама фоновая картинка приведена на рис. 2.
HTML5 CSS3 IE Cr Op Sa Fx
Объектная модель
[window.]document.getElementById(» elementID «).style.backgroundRepeatБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
Значения round и space поддерживаются только в IE9 и Opera 11.0.
CSS по теме
CSS Background Image Repeat
By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like this:
Example
If the image above is repeated only horizontally ( background-repeat: repeat-x; ), the background will look better:
Example
Tip: To repeat an image vertically, set background-repeat: repeat-y;
CSS background-repeat: no-repeat
Showing the background image only once is also specified by the background-repeat property:
Example
Show the background image only once:
In the example above, the background image is placed in the same place as the text. We want to change the position of the image, so that it does not disturb the text too much.
CSS background-position
The background-position property is used to specify the position of the background image.
Example
Position the background image in the top-right corner:
body <
background-image: url(«img_tree.png»);
background-repeat: no-repeat;
background-position: right top;
>
The CSS Background Repeat and Position Properties
Property | Description |
---|---|
background-position | Sets the starting position of a background image |
background-repeat | Sets how a background image will be repeated |
background-repeat
Определяет, как будет повторяться фоновое изображение, установленное с помощью свойства background-image. Можно установить повторение рисунка только по горизонтали, по вертикали или в обе стороны. В CSS3 допустимо указывать несколько значений для каждого фона, перечисляя значения через запятую.
Синтаксис
background-repeat: no-repeat | repeat | repeat-x | repeat-y | inherit
= repeat-x | repeat-y | [repeat | space | round | no-repeat]
Допустимо указывать два значения, первое ключевое слово задаёт повторение по горизонтали, второе по вертикали.
Значения
no-repeat Устанавливает одно фоновое изображение в элементе без его повторений, положение которого определяется свойством background-position (по умолчанию в левом верхнем углу). Аналогично no-repeat no-repeat . repeat Фоновое изображение повторяется по горизонтали и вертикали. Аналогично repeat repeat . repeat-x Фоновый рисунок повторяется только по горизонтали. Аналогично repeat no-repeat . repeat-y Фоновый рисунок повторяется только по вертикали. Аналогично no-repeat repeat . inherit Наследует значение родителя. space Изображение повторяется столько раз, чтобы полностью заполнить область; если это не удаётся, между картинками добавляется пустое пространство. round Изображение повторяется так, чтобы в области поместилось целое число рисунков; если это не удаётся сделать, то фоновые рисунки масштабируются.
XHTML 1.0 CSS 2.1 IE Cr Op Sa Fx
Даже опытному верстальщику приходится иногда смотреть свой код на наличие опечаток и ошибок. Так что не брезгуй проверять код валидатором, это поможет избежать множества ляпов в будущем.
Результат данного примера показан на рис. 1.
Рис. 1. Повторение фона по горизонтали
Сама фоновая картинка приведена на рис. 2.
HTML5 CSS3 IE Cr Op Sa Fx
Объектная модель
[window.]document.getElementById(» elementID «).style.backgroundRepeatБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
Значения round и space поддерживаются только в IE9 и Opera 11.0.
CSS по теме
CSS background-position Property
The background-position property sets the starting position of a background image.
Tip: By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
Default value: | 0% 0% |
---|---|
Inherited: | no |
Animatable: | yes. Read about animatable Try it |
Version: | CSS1 |
JavaScript syntax: | object.style.backgroundPosition=»center» 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 |
---|---|---|
left top left center left bottom right top right center right bottom center top center center center bottom | If you only specify one keyword, the other value will be «center» | Demo ❯ |
x% y% | The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. Default value is: 0% 0% | Demo ❯ |
xpos ypos | The first value is the horizontal position and the second value is the vertical. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions | 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
How to position a background-image to be centered at top:
body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
>
Example
How to position a background-image to be bottom right:
body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: bottom right;
>
Example
How to position a background-image using percent:
body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50% 50%;
>
Example
How to position a background-image using pixels:
body <
background-image: url(‘w3css.gif’);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 50px 150px;
>
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 ]