- CSS Background Image Repeat
- Example
- Example
- CSS background-repeat: no-repeat
- Example
- CSS background-position
- Example
- The CSS Background Repeat and Position Properties
- CSS background-repeat Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- Example
- Example
- HTML Background Images
- Background Image on a HTML element
- Example
- Example
- Background Image on a Page
- Example
- Background Repeat
- Example
- Example
- Background Cover
- Example
- Background Stretch
- Example
- Learn More CSS
- background-repeat
- Интерактивный пример
- Синтаксис
- Значения
- Примеры
- HTML
- CSS
- Результат
- Спецификация
- Поддержка браузеров
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
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 |
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 */
>
HTML Background Images
A background image can be specified for almost any HTML element.
Background Image on a HTML element
To add a background image on an HTML element, use the HTML style attribute and the CSS background-image property:
Example
Add a background image on a HTML element:
You can also specify the background image in the element, in the section:
Example
Specify the background image in the element:
Background Image on a Page
If you want the entire page to have a background image, you must specify the background image on the element:
Example
Add a background image for the entire page:
Background Repeat
If the background image is smaller than the element, the image will repeat itself, horizontally and vertically, until it reaches the end of the element:
Example
To avoid the background image from repeating itself, set the background-repeat property to no-repeat .
Example
Background Cover
If you want the background image to cover the entire element, you can set the background-size property to cover.
Also, to make sure the entire element is always covered, set the background-attachment property to fixed:
This way, the background image will cover the entire element, with no stretching (the image will keep its original proportions):
Example
Background Stretch
If you want the background image to stretch to fit the entire element, you can set the background-size property to 100% 100% :
Try resizing the browser window, and you will see that the image will stretch, but always cover the entire element.
Example
Learn More CSS
From the examples above you have learned that background images can be styled by using the CSS background properties.
To learn more about CSS background properties, study our CSS Background Tutorial.
background-repeat
Свойство background-repeat устанавливает, как фоновые изображения будет повторяться. Они могут повторяться по горизонтальной и вертикальной оси или не повторяться вовсе.
Интерактивный пример
Исходный код этого интерактивного примера хранится в репозитории GitHub. Если вы хотите внести свой вклад в проект интерактивных примеров, пожалуйста, клонируйте https://github.com/mdn/interactive-examples и отправьте нам запрос на извлечение.
По умолчанию, изображения обрезаются по размеру элемента, но их можно масштабировать (используя round ) или равномерно растянуть от конца к концу (используя space ).
Синтаксис
/*Ключевые значения*/ background-repeat: repeat-x; background-repeat: repeat-y; background-repeat: repeat; background-repeat: space; background-repeat: round; background-repeat: no-repeat; /*Два значения: горизонтальное | вертикальное*/ background-repeat: repeat space; background-repeat: repeat repeat; background-repeat: round space; background-repeat: no-repeat round; /* Глобальные значения */ background-repeat: inherit; background-repeat: initial; background-repeat: unset;
Значения
-
-
: Следующие однозначные имеют двухзначные эквиваленты: 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 В двухзначном синтаксисе первое означает горизонтальные повторения, а второе вертикальные. repeat Изображения повторяются столько, сколько необходимо, чтобы полностью покрыть область элемента, последнее обрезается, если не хватает места. space Изображение повторяется в заданном направлении столько раз, сколько необходимо, чтобы покрыть большую часть области рисования фонового изображения, не обрезая изображение. Оставшееся незакрытое пространство равномерно распределено между изображениями. Первое и последнее изображения касаются края элемента. Значение CSS-свойства background-position игнорируется для рассматриваемого направления, за исключением случаев, когда отдельное изображение больше области рисования фонового изображения, что является единственным случаем, когда изображение может быть обрезано, когда используется значение space . round Изображение повторяется в заданном направлении столько раз, сколько необходимо, чтобы покрыть большую часть области рисования фонового изображения, не обрезая изображение. Если оно не покрывает точно область, плитки изменяются в этом направлении, чтобы соответствовать ей. no-repeat Изображение не повторяется (и, следовательно, область рисования фонового изображения не обязательно будет полностью покрыта). Расположение неповторяющегося фонового изображения определяется CSS-свойством background-position .
Примеры
HTML
ol> li>no-repeat div class="one"> div> li> li>repeat div class="two"> div> li> li>repeat-x div class="three"> div> li> li>repeat-y div class="four"> div> li> li>repeat-x, repeat-y (multiple images) div class="five"> div> li> ol>
CSS
/* Совместно для всех DIVS в примере */ li margin-bottom: 12px;> div background-image: url(starsolid.gif); width: 144px; height: 84px; > /* повторение фона CSS */ .one background-repeat: no-repeat; > .two background-repeat: repeat; > .three background-repeat: repeat-x; > .four background-repeat: repeat-y; > /* Несколько изображений */ .five background-image: url(starsolid.gif), url(https://developer.mozilla.org/static/img/favicon32.png); background-repeat: repeat-x, repeat-y; height: 144px; >
Результат
В этом примере каждому элементу списка соответствует другое значение background-repeat .
Спецификация
Начальное значение repeat Применяется к все элементы. Это также применяется к ::first-letter и ::first-line . Наследуется нет Обработка значения список, каждый элемент которого содержит 2 ключевых слова, по одному на размер Animation type discrete Поддержка браузеров
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 22 февр. 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. -