- Как сделать, чтобы фон не повторялся?
- Решение
- Описание
- CSS по теме
- Популярные рецепты
- 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
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS по теме
- CSS background-repeat Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- Example
- Example
Как сделать, чтобы фон не повторялся?
Добавить фоновую картинку так, чтобы она не повторялась по горизонтали и вертикали.
Решение
Используйте свойство background со значением no-repeat для селектора body .
Описание
По умолчанию фоновая картинка повторяется по горизонтали и вертикали, выстраиваясь мозаикой на всём поле веб-страницы. Однако такое поведение фона не всегда требуется, поэтому на помощь придёт значение no-repeat , добавляемое к стилевому свойству background .
Общий синтаксис в этом случае будет следующий.
В данном случае фон добавляется к веб-странице, исходно располагаясь в левом верхнем углу окна браузера и отображается единственный раз, т.е. без повторений. В примере 1 показано, как это сделать конкретно.
HTML5 CSS 2.1 IE Cr Op Sa Fx
Содержимое веб-страницы
Результат данного примера показан на рис. 1.
Рис. 1. Фоновая картинка на веб-странице без повторения
CSS по теме
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Популярные рецепты
Как добавить картинку на веб-страницу?
Как добавить иконку сайта в адресную строку браузера?
Как добавить фоновый рисунок на веб-страницу?
Как сделать обтекание картинки текстом?
Как растянуть фон на всю ширину окна?
Как выровнять фотографию по центру веб-страницы?
Как разместить элементы списка горизонтально?
Как убрать подчеркивание у ссылок?
Как убрать маркеры в маркированном списке?
Как изменить расстояние между строками текста?
Как сделать, чтобы картинка менялась при наведении на нее курсора мыши?
Как открыть ссылку в новом окне?
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-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-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 */
>