How to set background image css
How to set background image css
background-image
The background-image CSS property sets one or more background images on an element.
Try it
The background images are drawn on stacking context layers on top of each other. The first layer specified is drawn as if it is closest to the user.
The borders of the element are then drawn on top of them, and the background-color is drawn beneath them. How the images are drawn relative to the box and its borders is defined by the background-clip and background-origin CSS properties.
If a specified image cannot be drawn (for example, when the file denoted by the specified URI cannot be loaded), browsers handle it as they would a none value.
Syntax
Each background image is specified either as the keyword none or as an value.
To specify multiple background images, supply multiple values, separated by a comma:
Values
Is a keyword denoting the absence of images.
Is an denoting the image to display. There can be several of them, separated by commas, as multiple backgrounds are supported.
Accessibility concerns
Browsers do not provide any special information on background images to assistive technology. This is important primarily for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page’s overall purpose, it is better to describe it semantically in the document.
Formal definition
Formal syntax
Examples
Layering background images
Note that the star image is partially transparent and is layered over the cat image.
2.10. CSS-фон
Каждый блок html-элемента имеет фоновый слой, который может быть полностью прозрачным (по умолчанию) или заполнен цветом и/или одним или несколькими изображениями. CSS-свойства фона указывают, какой цвет background-color и изображения background-image использовать, а также их размер, расположение, способ укладки и т.д.
Фон не отображается у пустых элементов с нулевой высотой. Отрицательные значения свойства margin не влияют на фон элемента.
Свойства фона html-элементов
1. Базовый цвет: свойство background-color
Свойство background-color устанавливает цвет фона элемента. Цвет рисуется за фоновыми изображениями. Для блочных элементов цвет фона распространяется на всю ширину и высоту блока элемента, для строчных — только на область их содержимого.
Цвет фона обрезается в соответствии со значением background-clip самого нижнего слоя фонового изображения.
Свойство не наследуется.
Рис. 1. Свойство background-color для разных элементов
2. Источник изображения: свойство background-image
Свойство background-image устанавливает фоновое изображение (одно или несколько) элемента. Значение none считается слоем изображения, но ничего не рисует. Изображение, которое является пустым (нулевой ширины или нулевой высоты), которое не загружается или не может быть отображено (например, потому что оно не в поддерживаемом формате изображения) также считается слоем, но ничего не рисует.
Свойство не наследуется.
3. Укладка изображений: свойство background-repeat
Свойство background-repeat определяет, как фоновые изображения укладываются в области фона после того, как для них установлены размеры и позиционирование. Если значение свойства имеет два ключевых слова, первое используется для горизонтального направления, второе — для вертикального.
Свойство не наследуется.
Рис. 2. Свойство background-repeat
4. Фиксация изображения: свойство background-attachment
Свойство background-attachment указывает, является ли фоновое изображение фиксированными относительно области просмотра или прокручивается вместе с элементом или его содержимым.
Свойство не наследуется.
background-attachment | |
---|---|
Значения: | |
scroll | Фоновое изображение прокручивается вместе с текстом и другим содержимым. Значение по умолчанию. |
fixed | Предотвращает перемещение, фиксирует фоновое изображение на заднем плане. |
local | Фоновое изображение прокручивается вместе с содержимым элемента. |
initial | Устанавливает значение свойства в значение по умолчанию. |
inherit | Наследует значение свойства от родительского элемента. |
5. Позиционирование изображений: свойство background-position
Если для элемента заданы фоновые изображения, свойство background-position указывает их начальное положение (после любого изменения размера) в соответствующей области расположения фона.
Свойство не наследуется.
Пара ключевых слов может быть переупорядочена, в то время как комбинация ключевого слова и длины или процента не может. Например, center left — допустимое значение, а 50% left — нет.
Положительные значения смещают внутрь от края области расположения фона. Отрицательные значения смещают наружу от края области расположения фона.
Рис. 3. Свойство background-position
Можно задать фоновую картинку так, чтобы она располагалась только по низу блока:
Рис. 4. Фоновое изображение по низу блока
Также благодаря свойству позиционирования, для одного блока можно использовать несколько фоновых изображений:
Рис. 5. Задание для блока нескольких фоновых изображений
6. Область рисования: свойство background-clip
Свойство background-clip определяет область рисования фона. Фон всегда рисуется под рамкой элемента, если таковая имеется.
Корневой элемент имеет другую область рисования фона, поэтому свойство background-clip на него не влияет.
Свойство не наследуется.
background-clip | |
---|---|
Значения: | |
border-box | Фон закрашивает область в пределах рамки элемента. Значение по умолчанию. |
padding-box | Фон закрашивает область в пределах внутренних полей элемента. |
content-box | Фон закрашивает только область содержимого. |
initial | Устанавливает значение свойства в значение по умолчанию. |
inherit | Наследует значение свойства от родительского элемента. |
Рис. 6. Свойство background-clip
7. Область расположения фона: свойство background-origin
Свойство background-origin указывает область расположения фона для элементов, которые выводятся на экране как единый блок (например, не абзацы текста).
Свойство не наследуется.
background-origin | |
---|---|
Значения: | |
padding-box | Фон позиционируется относительно верхних границ области внутренних полей элемента. Значение по умолчанию. |
border-box | Фон позиционируется относительно верхних границ рамки элемента. |
content-box | Фон позиционируется относительно верхних границ области содержимого элемента. |
initial | Устанавливает значение свойства в значение по умолчанию. |
inherit | Наследует значение свойства от родительского элемента. |
Рис. 7. Свойство background-origin
8. Размер изображений: свойство background-size
Свойство background-size устанавливает размер фоновых изображений.
Свойство не наследуется.
Рис. 8. Свойство background-size
9. Краткая запись свойств фона: свойство background
10. Множественные фоны
Первое изображение в списке — это слой, отображаемый ближайший к пользователю, следующий отрисовывается за первым, и так далее. Цвет фона, если он есть, закрашивается под всеми остальными слоями.
Рис. 9. Пример использования нескольких фоновых изображений
CSS Backgrounds
The CSS background properties are used to add background effects for elements.
In these chapters, you will learn about the following CSS background properties:
CSS background-color
The background-color property specifies the background color of an element.
Example
The background color of a page is set like this:
With CSS, a color is most often specified by:
Look at CSS Color Values for a complete list of possible color values.
Other Elements
You can set the background color for any HTML elements:
Example
div <
background-color: lightblue;
>
p <
background-color: yellow;
>
Opacity / Transparency
Example
Note: When using the opacity property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read.
Transparency using RGBA
If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:
An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.
CSS background-image Property
Example
Set a background-image for the element:
Example
Set two background images for the element:
More «Try it Yourself» examples below.
Definition and Usage
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.
Note: IE8 and earlier do not support multiple background images.
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:
Example
Use different background properties to create a «hero» image:
Example
Sets a linear-gradient (two colors) as a background image for a
Example
Sets a linear-gradient (three colors) as a background image for a
Example
The repeating-linear-gradient() function is used to repeat linear gradients:
Example
Sets a radial-gradient (two colors) as a background image for a
Example
Sets a radial-gradient (three colors) as a background image for a
Example
The repeating-radial-gradient() function is used to repeat radial gradients:
CSS Background Image
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
Example
The CSS Background Image Property
Property | Description |
---|---|
background-image | Sets the background image for an element |
We just launched
W3Schools videos
COLOR PICKER
Get certified
by completing
a course today!
CODE GAME
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
Web Courses
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.