- background-image
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Layering background images
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- 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
- Значения
- Повторное изображение
- Размер изображения
- Наследование
- Примеры использования
- Нюансы использования
- Материалы по теме
- When to Use HTML Tag and CSS background-image Property
- HTML Tag
- Example of using the HTML tag:
- CSS background-image Property
- Example of using the CSS background-image property:
- Any tag for the background image?
- How can I add background color to ‘img’ tag?
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.
Note: Even if the images are opaque and the color won’t be displayed in normal circumstances, web developers should always specify a background-color . If the images cannot be loaded—for instance, when the network is down—the background color will be used as a fallback.
Syntax
background-image: linear-gradient( to bottom, rgba(255, 255, 0, 0.5), rgba(0, 0, 255, 0.5) ), url("catfront.png"); /* Global values */ background-image: inherit; background-image: initial; background-image: revert; background-image: revert-layer; background-image: unset;
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.
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
Initial value | none |
---|---|
Applies to | all elements. It also applies to ::first-letter and ::first-line . |
Inherited | no |
Computed value | as specified, but with url() values made absolute |
Animation type | discrete |
Formal syntax
Examples
Layering background images
Note that the star image is partially transparent and is layered over the cat image.
HTML
div> p class="catsandstars">This paragraph is full of catsbr />and stars.p> p>This paragraph is not.p> p class="catsandstars">Here are more cats for you.br />Look at them!p> p>And no more.p> div>
CSS
p font-size: 1.5em; color: #fe7f88; background-image: none; background-color: transparent; > div background-image: url("mdn_logo_only_color.png"); > .catsandstars background-image: url("startransparent.gif"), url("catfront.png"); background-color: transparent; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Implementing image sprites in CSS
- Image-related data types: ,
- Image-related functions:
- cross-fade()
- element()
- image()
- image-set()
- linear-gradient()
- radial-gradient()
- conic-gradient()
- repeating-linear-gradient()
- repeating-radial-gradient()
- repeating-conic-gradient()
- paint()
- url()
Found a content problem with this page?
This page was last modified on Jul 20, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.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-image
background-image позволяет добавить изображение в качестве фона для выбранного элемента. Фоновое изображение может быть любого типа и повторяться или масштабироваться в зависимости от настроек.
Значения
- url(‘путь_к_изображению’) — указывает путь к изображению. Вы можете указать относительный путь к изображению на вашем сервере или абсолютный URL для изображения в интернете.
- none — значение по умолчанию, где нет фона. Если не хотите использовать изображение в качестве фона, вы можете установить background-image: none; .
- linear-gradient() , radial-gradient() , repeating-linear-gradient() , repeating-radial-gradient() — создают градиент фона без использования изображений. Можно определить цветовую палитру и ориентацию градиента.
Повторное изображение
background-repeat: repeat; — значение по умолчанию, изображение повторяется по горизонтали и вертикали. Изображение будет заполнять фон элемента, повторяясь при необходимости.
background-repeat: repeat-x; — повторяется только по горизонтали.
background-repeat: repeat-y; — повторяется только по вертикали.
background-repeat: no-repeat; — отображается только один раз без повторения.
Размер изображения
background-size: auto; — отображается в своём естественном размере.
background-size: cover; — масштабируется так, чтобы полностью заполнить фон элемента, возможно, обрезая его.
background-size: contain; — масштабируется так, чтобы полностью поместиться в фон элемента без искажений. Белые полосы могут появиться по краям фона, если пропорции изображения и фона не совпадают.
Наследование
Свойство background-image не наследуется дочерними элементами. Каждый элемент должен самостоятельно задавать фоновое изображение.
Примеры использования
Добавление изображения на фон определённого элемента
Добавление повторяющегося изображения на фон элемента
Добавление градиента на фон
Нюансы использования
- Фоновые картинки не будут автоматически масштабироваться под размеры родительского элемента. Если размеры картинки и родительского элемента не совпадают, то картинка обрежется или начнёт повторяться.
- Если задать цвет фона и background-image для одного элемента, то картинка будет отображаться поверх цвета фона.
⭐ Поддержка браузерами свойства background-image
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
When to Use HTML
Tag and CSS background-image Property
There are many situations when both the HTML tag and CSS background-image property give the same visual outcome. But what is the difference between them? Well, in this snippet, we’re going to discuss the differences between them, after which you can make a better decision when using them.
Use the
tag when you want to display a standalone image that is an essential part of the content on the page. This is particularly true when you want search engines to be able to index and display the image in search results. The
tag has several attributes that allow you to specify the image source, alt text, and other properties that are important for accessibility and SEO.
Use the CSS background-image property when you want to display an image as a background for an element, such as a div or a section. This is useful when you want to add a decorative background image that is not essential to the content, or when you want to create complex layouts that use images as part of the design.
The choice between using the
tag and the CSS background-image property depends on the specific needs of your web page. In general, use the
tag when the image is an essential part of the content, and use the CSS background-image property when the image is used for decorative or design purposes.
HTML
Tag
Use the
tag in the following cases:
- When it is not just a design element, but also a part of the content, such as a diagram, logo, or a person.
- When you expect that people will print your page and want the image to be included by default.
- When you want to be indexed by the search engine. Google doesn’t index background images automatically. Browsers don’t provide any information on background images to assistive technology. But using the
tag with the alt and title attributes will help to be recognised by screen readers.
- When the image has an essential semantic meaning (e.g., a warning icon). The use of an
tag will ensure that the meaning can be communicated in all user agents.
- When you rely on browser scaling for rendering an image in proportion with the text size.
- When you want to improve animation performance over a background.
Example of using the HTML
tag:
html> html> head> title>Title of the document title> head> body> h2>Example h2> img src="https://images.unsplash.com/photo-1585409677983-0f6c41ca9c3b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Nature" width="500" height="333"> body> html>
CSS background-image Property
Use the CSS background-image property in the following cases:
- If the image is only used for design.
- If the image isn’t a part of the content.
- If you expect that people can print your page, and don’t want the image to be included by default.
- If you want to improve the download time (as with CSS sprites).
- If you need to make visible only a part of the image.
- If you want to make an image-replacement of a text.
- If you need to stretch the background image to fill its whole window. Use with the background-size set to “cover”.
- If there is a need to repeat images.
Let’s see an example with the background-image property, where it is used with the background-size property with the “cover” value.
Example of using the CSS background-image property:
html> html> head> title>Title of the document title> style> .image < background-image: url("https://images.unsplash.com/photo-1433838552652-f9a46b332c40?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"); background-color: #cccccc; height: 500px; background-position: center; background-repeat: no-repeat; background-size: cover; position: relative; > style> head> body> div class="image"> div> body> html>
Any tag for the background image?
The HTML tag for adding a background image to an element is not a standalone tag, but it is an attribute called style . You can use this attribute to set the background-image property and specify the URL of the image file you want to use as a background.
How can I add background color to ‘img’ tag?
To add a background color to an
tag, you can use the CSS background-color property. However, keep in mind that this will only change the background color of the area around the image, not the image itself. If you want to change the color of the image itself, you would need to edit the image file using an image editor.
Here’s an example of how to use the background-color property to add a background color to an
tag:
html> html> head> title>Image Background Color Example title> head> body> img src="https://images.pexels.com/photos/1766838/pexels-photo-1766838.jpeg?auto=compress&cs=tinysrgb&w=600" style="background-color: yellow; padding: 10px;"> body> html>