background-repeat
Определяет, как будет повторяться фоновое изображение, установленное с помощью свойства background-image. Можно установить повторение рисунка только по горизонтали, по вертикали или в обе стороны. В CSS3 допустимо указывать несколько значений для каждого фона, перечисляя значения через запятую.
Синтаксис
background-repeat: no-repeat | repeat | repeat-x | repeat-y | inherit
background-repeat: [ , ]*
= 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
background-repeat Даже опытному верстальщику приходится иногда смотреть свой код на наличие опечаток и ошибок. Так что не брезгуй проверять код валидатором, это поможет избежать множества ляпов в будущем.
Результат данного примера показан на рис. 1.
Рис. 1. Повторение фона по горизонтали
Сама фоновая картинка приведена на рис. 2.
Рис. 2. Фон для блока
HTML5 CSS3 IE Cr Op Sa Fx
background-repeat
Объектная модель
[window.]document.getElementById(» elementID «).style.backgroundRepeat
Браузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
Значения round и space поддерживаются только в IE9 и Opera 11.0.
CSS по теме
Как сделать у изображения плавный :hover?
Есть два изображения для ссылки. Нужно что бы один фон ссылки, в виде изображения переходил плавно во второе.
Отслеживать
задан 21 фев 2014 в 6:52
177 3 3 серебряных знака 13 13 бронзовых знаков
css crossfade по-моему только в chrome работает всё ещё, можно через opacity сделать что на css что на js.
21 фев 2014 в 6:59
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
Вот примеры на css:
Label Label
switchedBackground < width: 300px; height: 200px; position: relative; display: block; >.switchedBackground .bg1 , .switchedBackground .bg2 < width: 100%; height: 100%; position: absolute; top: 0; left:0; transition: all 2s; >.switchedBackground .bg1 < background: url('http://placehold.it/300x200/000/00ee00&text=1'); opacity:1; >.switchedBackground .bg2 < background: url('http://placehold.it/300x200/000/00ee00&text=2'); opacity:0; >.switchedBackground .label < margin: auto; position: absolute; top: 0; >.switchedBackground:hover .bg2 < opacity: 1; >/* только в chrome */ .switchedBackground2 < width: 300px; height: 200px; display: block; background: url('http://placehold.it/300x200/000/00ee00&text=3'); transition: all 3s; >.switchedBackground2:hover < background: url('http://placehold.it/300x200/000/00ee00&text=4'); transition: all 3s; >
Отслеживать
ответ дан 21 фев 2014 в 7:19
18.1k 20 20 серебряных знаков 42 42 бронзовых знака
тогда уж не transition all, a transition background или transition opacity
21 фев 2014 в 7:24
это ваше дело, я писал просто чтобы показать как надо, а не для копипасты.
21 фев 2014 в 7:26
eicto спасибо, идея крутая! css3.bradshawenterprises.com/cfimg — здесь нашел интересные решения думаю как вот все к ссылке применить.
21 фев 2014 в 9:00
css
.example, .example::after, .example > span < display: block; height: 50px; width: 200px; >.example < background-image: url(http://placehold.it/200x50/09c/09c.png); position: relative; > .example::after < background-image: url(http://placehold.it/200x50/c90/c90.png); content: ""; opacity: 1; -webkit-transition: opacity 0.5s ease-in-out; -moz-transition: opacity 0.5s ease-in-out; -o-transition: opacity 0.5s ease-in-out; transition: opacity 0.5s ease-in-out; > .example:hover::after < opacity: 0; -webkit-transition: opacity 0.5s ease-in-out; -moz-transition: opacity 0.5s ease-in-out; -o-transition: opacity 0.5s ease-in-out; transition: opacity 0.5s ease-in-out; >.example::after, .example > span < position: absolute; >.example > span < color: #000; line-height: 50px; text-align: center; z-index: 2; >.example:hover > span
Отслеживать
ответ дан 21 фев 2014 в 9:28
19.9k 5 5 золотых знаков 44 44 серебряных знака 61 61 бронзовый знак
Шикарный метод. надо теперь с цветом текста разобраться а то его в начале вообще не видно.
21 фев 2014 в 10:25
@mace, его не из-за цвета не было видно. Попробуйте так. Обновил пример.
21 фев 2014 в 10:45
- html
- css
- javascript
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как настроить background image в css

CSS Background Image is defined as a CSS property to set background images for an element.The image can be applied as graphics or gradient of an element. This property is assigned inside an HTML page and can be done to block elements and inline. The core benefit of this property is it allows to place additional HTML content on top of the page like headings and also provides layering capabilities so that we have an option to add other image and text content as well within the same available space.
Syntax:
Web development, programming languages, Software testing & others
The background image takes four parameters:
URL: Using an image in the page is pretty simple by using url() value which provides a file path of an image. We can also set URI for the url().
How to Add Background Image in CSS using Various Methods?
Let’s see how the background image includes some methods in an HTML.
1. Using Inline CSS: The easiest and robust method is this one which uses background-image property with element.
2. Using Embedded CSS: It is referenced using class or Id part.
Background images could be performed using properties like:
- background-repeat: This method comes along with background-image and specifies how the background image should repeat or not. It takes some possible values like no-repeat (doesn’t repeat the image), repeat-x(tiles the image horizontally), repeat-y(tiles the image vertically).
- background-position: This ultimately specifies the position of the background image to be located with the values to be taken like a top, bottom, right, left, centre and the combinations of these values (ex: left bottom). The horizontal and vertical values could be combined by any needs.
- background-size: It specifies the size of the image to be placed and allows to have control of the size. Following are the values to be assigned for the background-size:
- auto: It’s a default value size.
- length: it allows to specify the width and height of an image in pixels (10 px 30px).
- cover: Zooming the background image completely by which an area of an element is covered with the entire background image avoiding some parts of the image by scaling it.
- Percentage: Specifies the width and height of an image in percentage. (10 % 30%)
- Centre: image to be placed in the centre.
Background images cannot be any static images we can also provide movement images like animated gifs too.
Examples to Implement CSS Background Image
Below are the example of CSS Background Image:
Example #1
This example sets the background image completely.
Code:
back.html
Output:

Same code with altering the height and width of the image. The original image is diminished in the page according to the specification. here is the code that sets to the defined pixels.
Code:
ff.html
Code:
ff.css
.dem1
.dem2
Output:

Example #2
Setting two background Images.
Code:
Output:

Example #3
Specifying background requires image property, size like how we specified under #bg1 class. And providing CSS part on body covers the full HTML code to fit in the window screen.
Code:
background-image demo using Size Property
This is my Web Page
The original size is set to the background
Example specifying the Width
Here is my next page
Well, the dimensions are specified here
Output:

Example #4
Setting a full-size background with the position.
Code:
Full Background image
This demo shows full-height image by setting the container and scaling them perfectly to the screen
Using CSS we have to fit the image into the screen by setting the property size to cover.
Output:

Example #5
Using Exact Aspect ratio with Border property
Code:
fit.html
Code:
.css
So by the, is an original image is not blurred while scaling the images to fit the area. Here is the result for the above code.
Output:

Example #6
Adding text cover over the background image.
Code:
fit.html
Creating an HTML PAge with Background Image
This is a way to add background image for a web page using html.
In this case I used:
html
scales entire Background.
Output:

Conclusion
Therefore, in this tutorial, we have seen a simple way to code an image using CSS also we have learnt how that image fit the screen. Background image with CSS provides good features to the websites and the web designers feel good in their themes. So, at the end of this section, you will be able to customize the works with good effort.
Recommended Articles
This is a guide to CSS Background Image. Here we discuss a brief overview on CSS Background Image and its different examples along with its code implementation. You can also go through our other suggested articles to learn more –
Похожие публикации:
- Как отменить обтекание в css
- Как оформить кнопку в css
- Что такое basic в информатике
- Что такое display block в css
Можно ли сделать так, чтобы картинка background-image не обрезалась, выходя за пределы элемента?
Как сделать так, чтобы картинка в background-image не обрезалась, выходя за пределы элемента, у которого установлено это свойство?
some text
.background
То есть, чтобы image.jpg не обрезалась, выходя за пределы p ? DEMO
Отслеживать
7,291 5 5 золотых знаков 27 27 серебряных знаков 69 69 бронзовых знаков
задан 11 мар 2015 в 16:49
151 1 1 золотой знак 1 1 серебряный знак 11 11 бронзовых знаков
Уточните. Она и не выйдет за пределы.
11 мар 2015 в 16:52
Еще как варант задать элементу паддинг с той стороны в которую вы хотите сдвинуть картинку
6 мая 2016 в 7:59
5 ответов 5
Сортировка: Сброс на вариант по умолчанию
Если кратко — нельзя.
Можно элементу min-width и min-height поставить согласно размерам картинки.
Если хотите, чтобы картинка выходила за пределы элемента, то расположите ее абсолютно в блоке.
Отслеживать
ответ дан 11 мар 2015 в 16:50
2,868 12 12 золотых знаков 56 56 серебряных знаков 103 103 бронзовых знака
Ну чтобы ничего никуда не вылазило за пределы с жестко указанными размерами для div не возможно. Поскольку это обычная геометрия и ее законы. Но сделать так чтобы лишнее пряталось и размер картинки не менялся возможно.
1) Ставим картинку в сам див, или что там у вас.
2) Делаем стили блоку.
.my-some-class
Недостаток подхода в том что width и height указывать нужно обязательно. Чтобы разместить текст над картинкой, ставим ей абсолютное позиционирование. И текст под картинку.
