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.
- MDN Understanding WCAG, Guideline 1.1 explanations
- Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0
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
background-image =
#
=
|
none
=
|
=
|
=
url( * ) |
=
src( * )
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
| Specification |
|---|
| CSS Backgrounds and Borders Module Level 3 # background-image |
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?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 20, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
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.Как добавить фон на страницу. CSS background-image
background-image позволяет добавить изображение в качестве фона для выбранного элемента. Фоновое изображение может быть любого типа и повторяться или масштабироваться в зависимости от настроек.
Синтаксис
selector
Значения
- 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 не наследуется дочерними элементами. Каждый элемент должен самостоятельно задавать фоновое изображение.
Примеры использования
Добавление изображения на фон определённого элемента:
Здесь паучок
.container < width: 600px; height: 300px; background-image: url('01.jpg'); background-size: cover; /* размер одного повторяющегося изображения */ >h1
Добавление повторяющегося изображения на фон элемента
Здесь паучок
.container < width: 600px; height: 300px; background-image: url('01.jpg'); background-repeat: repeat; >h1
Добавление градиента на фон
Здесь нет паучка
.container < width: 600px; height: 300px; background-image: linear-gradient(to right, #E2BCBB, #E4514A); >h1

Нюансы использования
- Фоновые картинки не будут автоматически масштабироваться под размеры родительского элемента. Если размеры картинки и родительского элемента не совпадают, то картинка обрежется или начнёт повторяться.
- Если задать цвет фона и background-image для одного элемента, то картинка будет отображаться поверх цвета фона.
⭐ Поддержка браузерами свойства background-image
Материалы по теме
- Как размыть картинку
- Обзор цветовых форматов в CSS
- Как передвинуть элемент на странице
- Как сделать фон на странице
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Читать дальше

Новое в 2023 — text-wrap: balance
В 2023 в CSS появилось любопытное свойство text-wrap со значением balance . Оно «уравновешивает» текстовые элементы, чтобы они приятнее выравнивались внутри блока.
Ограничение — текст не длиннее 6 строк, иначе браузеру придётся непросто, и лучше не применять это свойство к body .
Вот пример заголовка c text-wrap: balance и без него.
На момент написания заметки свойство поддерживается во всех больших браузерах, кроме Safari, а на мобильных — только в Chrome, но то ли ещё будет.
- 13 ноября 2023

Знакомство с CSS
После того как мы разобрались с базовой структурой веб-страницы с помощью HTML, пришло время привнести в неё стиль и красоту. В этом нам поможет CSS, что означает Cascading Style Sheets, или «каскадные таблицы стилей».
Что такое CSS?
CSS используется для оформления HTML-страниц. Если HTML — это скелет сайта, то CSS — его одежда. С помощью CSS мы можем задавать цвета, шрифты, отступы, добавлять анимации и многое другое.
Как подключить CSS к HTML
Есть несколько способов использования CSS внутри HTML:
Внутренний CSS: внутри раздела HTML-документа, в теге :
Внешний CSS: создание отдельного CSS-файла и его подключение с помощью элемента :
Инлайновые стили: непосредственно в HTML-элементе, через атрибут style . Но это не очень хороший способ, лучше его не использовать, и вот почему.
Этот текст будет красного цвета.
Основы синтаксиса CSS
CSS состоит из селекторов и объявлений. Селектор указывает, к какому элементу HTML применяется стиль, а объявление состоит из свойства и его значения.
/* Селектор */ p < /* Свойство : Значение; */ color: green; font-size: 14px; >Работа с цветом и фоном
Одни из самых основных свойств в CSS — это цвет и фон элементов.
color меняет цвет текста:
background-color меняет фоновый цвет элемента:
Типографика и шрифты
CSS позволяет нам контролировать шрифты на странице:
- font-family задаёт шрифт текста, даже если он нестандартный.
- font-size определяет размер текста.
- font-weight устанавливает жирность шрифта.
Блочная модель
Важной концепцией в CSS является блочная модель, которая включает в себя margin , border , padding , и content .
Внутренние и внешние отступы одной картинкой:
Позиционирование и Flexbox
Чтобы разместить элементы на странице, мы используем различные стратегии позиционирования, включая флексбоксы, которые позволяют нам упростить многие задачи.
.container < display: flex; /* Применяем Flexbox */ justify-content: center; /* Центрирование содержимого по горизонтали */ align-items: center; /* Центрирование содержимого по вертикали */ >Адаптивный дизайн
С помощью медиа-запросов мы можем создавать адаптивный дизайн, чтобы наш сайт хорошо выглядел на разных устройствах.
@media (max-width: 600px) < .container < flex-direction: column; >>Это только начало пути в мир CSS, но зная эти основы, вы уже можете начать экспериментировать и применять стили к вашим веб-страницам. В следующей статье мы разберём JavaScript и увидим, как добавить интерактивность нашим веб-страницам. Удачи в творчестве и до новых встреч в коде!
- 1 ноября 2023

Увеличение ссылки при наведении
Задача: плавно увеличить ссылку при наведении.
Решение:
a < display: inline-block; transition: transform 0.3s ease; >a:hover
Первые два свойства просто немного меняют вид ссылки. Свойство color: maroon; меняет цвет текста в тегах на темно-красный, а свойство text-decoration : none; убирает подчеркивание.
Но наша задача — плавно увеличить размер ссылки, а не просто её перекрасить. Поэтому используем свойство transform: scale(1.2) , которое срабатывает при наведении курсора и увеличивает размер ссылки в 1.2 раза по сравнению с её начальным размером.
- 13 октября 2023

WOFF больше не нужен
Я купил и скачал шрифты для недавнего проекта, распаковал папку, где были только WOFF2-файлы, и сначала не поверил, что такое бывает.
Потом мне стало интересно: они что, забыли WOFF? А он вообще ещё нужен? Ну, всё-таки, веб — это место, где постоянно всё меняется и улучшается, поэтому я пошёл и спросил людей в Mastodon. Ответ был единодушным: нужен только WOFF2!
Я хорошо помню пост от Зака в конце 2016, после которого я отказался от исчерпывающего синтаксиса @font-face , включавшего, вдобавок, TTF, EOT и SVG-шрифты, и перешёл только на WOFF2 и WOFF.
Похоже, с тех пор мир веб-шрифтов изменился ещё разок, и вот актуальная версия @font-face :
@font-face
Остался всего один формат. Просто, скажите?
Как писал Зак, «так как в вебе, когда шрифт не найден, всё равно подгружаются системные шрифты, мы можем идти в ногу со временем». Итак, какие браузеры отправятся в тёмные века системных шрифтов с этим синтаксисом?
- IE 11, 10, 9, 8, 7, …
- Chrome 4–35
- Edge 12 и 13
- Safari 3–9.1
- Firefox 2–38
- Opera 22 и ниже
- Android 4.4.4 KitKat и ниже (а это
- Safari на iOS 3.2–9.3
Caniuse.com показывает, что почти у 95% пользователей есть браузер с поддержкой WOFF2. А в относительной статистике (Date Relative — прим. перев.) заметно, что массовый переход на WOFF2 случился в 2015 и 2016. К концу 2016 во всех последних версиях больших браузеров появилась поддержка WOFF2.3
А спустя 7 лет поддержка расширилась настолько, что можно уже не добавлять в проект WOFF-файлы — ну, кроме случая, когда вы точно знаете, что много ваших пользователей используют старые устройства и браузеры.
С другой стороны, нет смысла и удалять WOFF из старых проектов. Если вы подключали WOFF2 раньше WOFF внутри @font-face — и порядок здесь важен — то браузер просто скачает и подключит WOFF2-версию.
И если однажды вы, как и я, обнаружите себя перед папкой, полной файлов WOFF2, знайте, что WOFF — уже всё.
- 23 сентября 2023

Трясём пароль с помощью CSS
Знаете момент, когда всё на сайте уже сделано, и хочется добавить какую-нибудь маленькую незаметную фишку? Мы тоже знаем, поэтому давайте просто потрясём поле пароля, когда пользователь ввёл неверный пароль. Как на Маке.
Вот что получится в итоге:
- 7 сентября 2023

Как сделать тёмную тему на сайте
Без лишних слов создадим простой переключатель для светлой и темной темы с использованием HTML, CSS и JavaScript. Нам понадобятся три файла — index.html , styles.css и script.js .
HTML
Основная разметка страницы — заголовок, абзац текста, список и текст в рамке.
CSS (styles.css):
Здесь задаём цвета для светлой и тёмной темы, а ещё минимальную стилизацию текста и блока с рамкой.
body < font-family: Arial, sans-serif; transition: background-color 0.3s ease; >body.light-theme < background-color: #ffffff; color: #000000; >body.dark-theme < background-color: #121212; color: #ffffff; >.boxed-text
JavaScript (script.js)
Этот код нужен, чтобы переключать тему при нажатии на кнопку:
document.getElementById('themeToggle').addEventListener('click', function() < const currentTheme = document.body.className; if (currentTheme === 'light-theme') < document.body.className = 'dark-theme'; >else < document.body.className = 'light-theme'; >>);При загрузке страницы по умолчанию будет установлена светлая тема. При нажатии на кнопку «Переключить тему» будет происходить переключение между светлой и темной темой.
- 29 августа 2023

4 способа центрировать текст в CSS
Центрирование элементов на веб-странице — это одна из наиболее распространенных задач, с которой мы сталкиваемся при работе с макетами. И хотя центрирование текста по горизонтали довольно простое ( text-align: center; и делов-то), вертикальное центрирование может быть немного сложнее. Давайте рассмотрим несколько методов.
Метод 1: Flexbox
Flexbox — это один из самых простых и эффективных способов центрирования.
Заворачиваем текст в с классом center-both :
Центрированный текст
.center-both
Метод 2: CSS Grid
HTML такой же, как в предыдущем примере. В CSS включаем гриды и используем свойство place-items со значением center :
.center-both
Метод 3: позиционирование и Transform
Этот метод немного старомодный и работает не идеально. Здесь у div устанавливается relative позиция. А
внутри дива мы сдвигаем с помощью абсолютного позиционирования. Не слишком элегантно:
.center-both < position: relative; >.center-both p
HTML остается таким же. Вот что получается:
Плохой метод: использование line-height
Если у вас однострочный текст, вы можете установить line-height , равный высоте родительского элемента.
.center-both < line-height: 200px; /* Пример высоты */ text-align: center; >Этот метод не подойдет для многострочного текста. Да и вообще мы очень не рекомендуем так делать, это прям совсем для любителей острых ощущений. Потому что вот:
Если вам интересно узнать больше о каждом из этих методов, рекомендуем посмотреть документацию по Flexbox на MDN или документацию по CSS Grid на MDN, а ещё пройти курсы в HTML Academy.
- 28 августа 2023

Как скруглить рамку. CSS-свойство border-radius
CSS-свойство border-radius помогает скруглить углы элемента. Оно особенно полезно для стилизации кнопок, форм, карточек товаров и других элементов сайта.
- 28 июля 2023

CSS-свойство contain
Представьте, что у вас есть контейнер. Внутри него находятся разные элементы: текст, изображения или что-то другое. Свойство contain говорит браузеру, как именно элементы должны взаимодействовать. Например, они могут быть ограничены, влиять на расположение друг друга или менять свои размеры.
Также свойство помогает повысить производительность страницы. Например, браузер понимает, когда при изменении свойств элемента нужно перерисовать страницу, а когда нет.
⭐ CSS-свойство contain определяет, как элемент должен взаимодействовать с другими элементами внутри контейнера.
Синтаксис
.container
- 14 июля 2023

Как задать позицию и размер элемента. CSS-свойство inset
CSS-свойство inset задаёт позицию и размер элемента на странице. Это комбинация четырёх отдельных свойств: top , right , bottom и left , которые определяют отступы от верхнего, правого, нижнего и левого края элемента.
Синтаксис
.element
- 13 июля 2023
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.
Property background-image 1.0 4.0 1.0 1.0 3.5 CSS Syntax
background-image: url|none|initial|inherit;
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:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow);
>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:
#grad1 <
height: 200px;
background-color: #cccccc;
background-image: radial-gradient(red, yellow);
>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%);
>How to add SVGs with CSS (background-image)
There are TWO methods for displaying SVG images as a CSS background image:
- Link directly to an SVG file
.your-class < background-image: url( '/path/image.svg' ); >- Placing SVG code as the source.
.your-class < background-image: url( "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 600 200'%3E%3Cpath d='M10 10h123v123H10z'/%3E%3C/svg%3E" ); >Notice with this method we have to treat the SVG code before it will work. In the example, we convert the SVG to a Data URI. You could even convert it to Base64, but that will result in a messier, longer code blob. It is a best practice to avoid Base64 in this case.
Tip: Use this SVG to CSS converter tool to quickly convert your SVG code into a data URI.
After you place your file path or SVG code into the background-image property, you can further tweak how the background displays. You see, the great thing about using an SVG as a CSS background-image is that they can be styled with CSS background properties.
The CSS background-image properties
Let’s review all the properties related to background-image and what they do.
- Background-attachment:
Example values: scroll; fixed; local;
The attachment specifies how the background moves relative to the user’s screen. When the user scrolls, the background can scroll along with a given section, or stay put ( fixed ).
- Background-position:
Example values: center; top left; 50% 50%; right 30px bottom 15px;
The background-position determines where the image is displayed within its container. The center keyword is great with large backgrounds and at making patterns symmetrical. With smaller backgrounds, you may reach for a combo of keywords and lengths to place the background image more precisely. - Background-size:
Example values: cover; contain; 500px 250px; auto;
This controls how big or small the image displays. A value of cover forces the image to fill its entire containing element in proportion, and either the excess width or height will get clipped. A value of contain is similar in that it fills its container in proportion, but without clipping. You can also provide a specific width and height value. - Background-repeat:
Example values: no-repeat; repeat; repeat-x;
The background-repeat property allows you to tile the background image into a pattern. - Background-color:
Example values: red; #F00; rgb(0,255,165);
SVGs are a transparent image format and if the SVG elements do not cover the entire viewBox, the background color will be visible behind your SVG. - Background-origin:
Example values: border-box; padding-box; content-box;
The origin determines the boundary of the background’s container. Border-box will stretch the background area for the entire container, while the padding-box and content-box values shrink the background area within the border and inside the padding respectively.
- Background-clip:
Example values: border-box; padding-box; content-box;
Similar to background-origin , this property defines the background area, with one difference: the background doesn’t resize, but instead crops the background image to fit in the assigned boundary.
- Background-blend-mode:
Example values: multiply; screen; overlay, color-dodge, color;
This property blends the colors of the target background with what is visible behind the target element, blending into a single colorful result. The blend modes are essentially the browser version of Photoshop’s blending modes.
Layering multiple background images
Background-image can hold multiple background image layers to achieve cool effects. To create these image layers, comma-separate each image value in a single background-image property. Then when you use any related background properties, comma-separate those varied values to coincide with the images, or instead use a single value which will apply to all images the same.
background-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );You can mix images, SVG data URIs, and CSS gradients. But you need to overlap images with transparency or take advantage of the background-blend-mode discussed above. Otherwise you will only see one background. The first image is on top of the background stack.
Let’s mix a few backgrounds now, and see what we get. First I headed over to the homepage of SVGBackgrounds.com to find a few quick backgrounds to layer together. Here is the code and results:
BUT, this technique prevents the need to layer div containers to achieve a layer effect. Let’s try again, this time to make a simpler one that looks useable. Let’s place a pattern over a cool image texture.
Much better!
I could definitely see something more like this being used in a real-world project. Subtle backgrounds are always nice.
Wrapping up about SVGs in CSS background-images
We looked at how to add SVGs into the CSS property background-image . With all the related background properties and the fact you can layer backgrounds, there is little that can’t be achieved. This way of adding website backgrounds is powerful.
), the creator behind SVG Backgrounds. Hire me to help you with design on your website or app.
), the creator behind SVG Backgrounds. I produce free and paid resources every few months, sign up for alerts.
