- background-image
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS Background Image
- Example
- Example
- Example
- The CSS Background Image Property
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- CSS background-image Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Example
- Example
- 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-image
Устанавливает фоновое изображение для элемента. Если одновременно для элемента задан цвет фона, он будет показан, пока фоновая картинка не загрузится полностью. То же произойдет, если изображения не доступны или их показ в браузере отключен. В случае наличия в рисунке прозрачных областей, через них будет проглядывать фоновый цвет. В CSS3 допустимо указывать несколько фоновых изображений, перечисляя их параметры через запятую.
Синтаксис
background-image: url(путь к файлу) | none | inherit
background-image: url(путь к файлу) | none[, url(путь к файлу) | none]*
Значения
url В качестве значения используется путь к графическому файлу, который указывается внутри конструкции url() . Путь к файлу при этом можно писать как в кавычках (двойных или одинарных), так и без них. none Отменяет фоновое изображение для элемента. inherit Наследует значение родителя.
HTML5 CSS2.1 IE Cr Op Sa Fx
Объектная модель
[window.]document.getElementById(» elementID «).style.backgroundImageБраузеры
Internet Explorer до версии 7.0 включительно применяет фон к внутренней части границы элемента, у которого установлено свойство hasLayout . Если у элемента нет hasLayout , свойство background-image будет учитывать границы элемента, как это и задано в спецификации. Разница в отображении будет заметна, если границы пунктирные ( dashed или dotted ), а не сплошные.
Если для элемента значение overflow установлено как scroll или auto , в Internet Explorer 8 будет вертикальная задержка в один пиксел при прокрутке фона.
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
HTML5 CSS2.1 IE Cr Op Sa Fx
1 2 3
Результат данного примера в браузере Chrome показан на рис. 1. Браузер Internet Explorer, Opera и Firefox корректно отображают фон для строки (рис. 2).
Рис. 1. Повторение фона для каждой ячейки
Рис. 2. Фон для всей строки
CSS Background Image
The background-image property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element.
Example
Set the background image for a page:
Example
This example shows a bad combination of text and background image. The text is hardly readable:
Note: When using a background image, use an image that does not disturb the text.
The background image can also be set for specific elements, like the
element:
Example
The CSS Background Image Property
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
CSS background-image Property
The background-image property sets one or more background images for an element.
By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.
Tip: The background of an element is the total size of the element, including padding and border (but not the margin).
Tip: Always set a background-color to be used if the image is unavailable.
Default value: | none |
---|---|
Inherited: | no |
Animatable: | no. Read about animatable |
Version: | CSS1 + new values in CSS3 |
JavaScript syntax: | object.style.backgroundImage=»url(img_tree.gif)» 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 |
---|---|---|
url(‘URL‘) | The URL to the image. To specify more than one image, separate the URLs with a comma | Demo ❯ |
none | No background image will be displayed. This is default | |
conic-gradient() | Sets a conic gradient as the background image. Define at least two colors | Demo ❯ |
linear-gradient() | Sets a linear gradient as the background image. Define at least two colors (top to bottom) | Demo ❯ |
radial-gradient() | Sets a radial gradient as the background image. Define at least two colors (center to edges) | Demo ❯ |
repeating-conic-gradient() | Repeats a conic gradient | Demo ❯ |
repeating-linear-gradient() | Repeats a linear gradient | Demo ❯ |
repeating-radial-gradient() | Repeats a radial gradient | 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
Sets two background images for the element. Let the first image appear only once (with no-repeat), and let the second image be repeated:
body <
background-image: url(«img_tree.gif»), url(«paper.gif»);
background-repeat: no-repeat, repeat;
background-color: #cccccc;
>
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 */
>
Example
Sets a linear-gradient (two colors) as a background image for a element:
Example
Sets a linear-gradient (three colors) as a background image for a element:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow, green);
>
Example
The repeating-linear-gradient() function is used to repeat linear gradients:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-linear-gradient(red, yellow 10%, green 20%);
>
Example
Sets a radial-gradient (two colors) as a background image for a element:
Example
Sets a radial-gradient (three colors) as a background image for a element:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: radial-gradient(red, yellow, green);
>
Example
The repeating-radial-gradient() function is used to repeat radial gradients:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-radial-gradient(red, yellow 10%, green 20%);
>
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.