- background — repeat
- Кратко
- Пример
- Как пишется
- Подсказки
- На практике
- Алёна Батицкая советует
- 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
background — repeat
При помощи этого свойства и небольшой картинки можно создавать красивые паттерны на фоне.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Свойство background — repeat управляет повтором фонового изображения. По умолчанию значение этого свойства — repeat , то есть фоновая картинка будет повторяться по вертикали и по горизонтали.
Пример
Скопировать ссылку «Пример» Скопировано
div class="element">div>
.element height: 100vh; background-image: url(images/pattern.png); background-size: 64px auto;>
.element height: 100vh; background-image: url(images/pattern.png); background-size: 64px auto; >
Получился красивый паттерн. Изображение повторяется по горизонтали и по вертикали.
Изменим значение на repeat — x :
.element background-repeat: repeat-x;>
.element background-repeat: repeat-x; >
Теперь картинка повторяется только по горизонтали. Аналогично можно повторить картинку по вертикали при помощи значения repeat — y .
Но чаще всего в работе встречается значение no — repeat . С таким значением фоновая картинка не будет повторяться ни по горизонтали, ни по вертикали.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
В качестве значения для свойства background — repeat используются следующие ключевые слова:
- no — repeat — фоновое изображение не повторяется, остаётся только одно внутри элемента.
- repeat — изображение повторяется и по горизонтали, и по вертикали до тех пор, пока не заполнит всю площадь элемента (значение по умолчанию).
- repeat — x — фон повторяется по горизонтали.
- repeat — y — фон повторяется по вертикали.
- space — изображение повторяется до тех пор, пока не заполнит весь элемент. При этом, если по размерам не удаётся повторить изображение без обрезки, то между картинками добавляется равное пространство. Крайне редко требуется в работе.
- round — изображение повторяется так, чтобы заполнить весь элемент. Но картинка не обрезается, повторяется целое количество раз. Если это не удаётся, то картинка масштабируется. Крайне редко требуется в работе.
Ключевые слова repeat и no — repeat можно комбинировать, чтобы управлять повторениями по горизонтали (первое значение) и по вертикали (второе значение). Но проще указывать специальные ключевые слова repeat — x и repeat — y .
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Значение по умолчанию — repeat .
💡 Чаще всего для полноэкранных фонов указывается значение no — repeat .
💡 Свойство background — repeat нельзя анимировать 😒
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
background — repeat — свойство простое. Написано повторять — повторяем фон. Написано не повторять — не повторяем.
🛠 С помощью повторения фона и линейного градиента ( linear — gradient ) можно создавать полосатые фоны.
div class="element">div>
.element height: 100vh; background-image: linear-gradient( #49a16c 50px, #064236 0 ); background-size: 100% 100px; background-repeat: repeat-y;>
.element height: 100vh; background-image: linear-gradient( #49a16c 50px, #064236 0 ); background-size: 100% 100px; background-repeat: repeat-y; >
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 */
>