- background
- Try it
- Constituent properties
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Setting backgrounds with color keywords and images
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- background-color
- Try it
- Syntax
- Values
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Способы создания прозрачных фонов
- Как задать прозрачность?
- CSS свойство Opacity
- Использование PNG -картинки
- Формат системы RGBA
- Клетчатые изображения, или с уважением к истории
- Подытожим?
background
The background shorthand CSS property sets all background style properties at once, such as color, image, origin and size, or repeat method. Component properties not set in the background shorthand property value declaration are set to their default values.
Try it
Constituent properties
This property is a shorthand for the following CSS properties:
Syntax
/* Using a */ background: green; /* Using a and */ background: url("test.jpg") repeat-y; /* Using a and */ background: border-box red; /* A single image, centered and scaled */ background: no-repeat center/80% url("../img/image.png"); /* Global values */ background: inherit; background: initial; background: revert; background: revert-layer; background: unset;
The background property is specified as one or more background layers, separated by commas.
The syntax of each layer is as follows:
- Each layer may include zero or one occurrences of any of the following values:
- The value may only be included immediately after , separated with the ‘/’ character, like this: » center/80% «.
- The value may be included zero, one, or two times. If included once, it sets both background-origin and background-clip . If it is included twice, the first occurrence sets background-origin , and the second sets background-clip .
- The value may only be included in the last layer specified.
Values
See background-clip and background-origin . Default: border-box and padding-box respectively.
See background-color . Default: transparent .
The following three lines of CSS are equivalent:
background: none; background: transparent; background: repeat scroll 0% 0% / auto padding-box border-box none transparent;
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
- background-image : none
- background-position : 0% 0%
- background-size : auto auto
- background-repeat : repeat
- background-origin : padding-box
- background-clip : border-box
- background-attachment : scroll
- background-color : transparent
- background-position : refer to the size of the background positioning area minus size of background image; size refers to the width for horizontal offsets and to the height for vertical offsets
- background-size : relative to the background positioning area
- background-image : as specified, but with url() values made absolute
- background-position : as each of the properties of the shorthand:
- background-position-x : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
- background-position-y : A list, each item consisting of: an offset given as a combination of an absolute length and a percentage, plus an origin keyword
- background-color : a color
- background-image : discrete
- background-clip : a repeatable list of
- background-position : a repeatable list of
- background-size : a repeatable list of
- background-repeat : discrete
- background-attachment : discrete
Formal syntax
background =
[ # , ]?=
||
[ / ]? ||
||
||
||
=
||
||
[ / ]? ||
||
||
||
=
|
none=
[ left | center | right | top | bottom | ] |
[ left | center | right | ] [ top | center | bottom | ] |
[ center | [ left | right ] ? ] && [ center | [ top | bottom ] ? ]=
[ | auto ] |
cover |
contain=
repeat-x |
repeat-y |
[ repeat | space | round | no-repeat ]=
scroll |
fixed |
local=
border-box |
padding-box |
content-box=
|=
|=
url( * ) |
src( * )Examples
Setting backgrounds with color keywords and images
HTML
p class="topbanner"> Starry skybr /> Twinkle twinklebr /> Starry sky p> p class="warning">Here is a paragraphp> p>p>
CSS
.warning background: pink; > .topbanner background: url("starsolid.gif") #99f repeat-y fixed; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 18, 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.background-color
The background-color CSS property sets the background color of an element.
Try it
Syntax
/* Keyword values */ background-color: red; background-color: indigo; /* Hexadecimal value */ background-color: #bbff00; /* Fully opaque */ background-color: #bf0; /* Fully opaque shorthand */ background-color: #11ffee00; /* Fully transparent */ background-color: #1fe0; /* Fully transparent shorthand */ background-color: #11ffeeff; /* Fully opaque */ background-color: #1fef; /* Fully opaque shorthand */ /* RGB value */ background-color: rgb(255 255 128); /* Fully opaque */ background-color: rgb(117 190 218 / 0.5); /* 50% transparent */ /* HSL value */ background-color: hsl(50 33% 25%); /* Fully opaque */ background-color: hsl(50 33% 25% / 0.75); /* 75% opaque, i.e. 25% transparent */ /* Special keyword values */ background-color: currentcolor; background-color: transparent; /* Global values */ background-color: inherit; background-color: initial; background-color: revert; background-color: revert-layer; background-color: unset;
The background-color property is specified as a single value.
Values
The uniform color of the background. It is rendered behind any background-image that is specified, although the color will still be visible through any transparency in the image.
Accessibility concerns
It is important to ensure that the contrast ratio between the background color and the color of the text placed over it is high enough that people experiencing low vision conditions will be able to read the content of the page.
Color contrast ratio is determined by comparing the luminance of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.
Formal definition
Formal syntax
Examples
HTML
div class="exampleone">Lorem ipsum dolor sit amet, consectetuerdiv> div class="exampletwo">Lorem ipsum dolor sit amet, consectetuerdiv> div class="examplethree">Lorem ipsum dolor sit amet, consectetuerdiv>
CSS
.exampleone background-color: transparent; > .exampletwo background-color: rgb(153, 102, 153); color: rgb(255, 255, 204); > .examplethree background-color: #777799; color: #ffffff; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 18, 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.Способы создания прозрачных фонов
Вы хотите научиться создавать страницы с оригинальным и ярким современным дизайном? Применение полупрозрачных элементов способно помочь Вам в решении этой непростой задачи. Сегодня мы рассмотрим основные практические способы задания прозрачности структурных элементов.
Как задать прозрачность?
Если рассматривать данную тему сквозь призму исторического развития веб-технологий, то можно выделить следующие подходы:
- Свойство opacity.
- Использование PNG -картинки
- Формат системы RGBA
- Ну, и наконец, древность или клетчатые изображения.
CSS свойство Opacity
Применение стилевого CSS свойства оpacity позволяет задать прозрачность того элемента, к которому применяется. Значения, которые можно использовать в качестве аргумента изменяются в пределах от 0 до 1.
Рассмотрим пример.DOCTYPE html> html> head> title>TODO supply a titletitle> meta charset="UTF-8"> link rel="stylesheet" media="all" type="text/css" href="css/style2.css" /> head> body> div class=" prozrachen "> Тут будет много Вашего текста div> body> html>
body background: url(./vaden-pro-logo.png); /* Фон для тела страницы */ > . prozrachen padding: 10px; /*Отступы для текста*/ background: darkturquoise; /* Задаем цвет фона */ margin: 0 auto; /* Центрируем блок */ width: 50%; /* Задаем ширину блока */ opacity: 0.7; /* Задаем прозрачность */ font: 48px/64px Times New Roman; text-align: justify; >
В результате мы получили полупрозрачный блок:
- Opacity принимает значения из диапазона: 0 (полная прозрачность) — 1 (непрозрачность).
- Кросс-браузерность. В IE до седьмой версии включительно Opacity не поддерживается. Добиться одинакового отображения элемента поможет следующая строчка:
- с абсолютным позиционированием (position: absolute)
- с фиксированным линейным размером (height или width).
Для лучшего понимания материала последнего пункта, в предыдущем примере зададим тексту белый цвет
и рассмотрим его под микроскопом:
Как видим, контент нашего блока (текст) тоже стал полупрозрачным. Но что делать, если на практике прозрачность содержимого вас не интересует, а интересует лишь прозрачность фона? В таком случае, переходим к следующему пункту.
Использование PNG -картинки
Интересной особенностью формата PNG является то, что он имеет 256 уровней прозрачности. Думаю, Вы уловили ход мыслей, и наверняка уже построили алгоритм работы такого подхода. Мне остается только его озвучить.
- Создаем в Photoshop, однотонную полупрозрачную картинку (назовем ее transparent) и сохраняем в формате png.
- Используем ее в качестве бэкграунда:
body background: url(./vaden-pro-logo.png); > .prozrachen padding: 10px; background: url(./transparent.png); margin: 0 auto; width: 50%; font: 48px/64px Times New Roman; color: white;li> text-align: justify; >
В результате мы получили блок с прозрачным фоном и непрозрачным содержимым:
- В отличии от свойства opacity прозрачность задается только для фона
- Кросс-браузерность. Работает почти во всех браузерах, и это плюс. Но прозрачность PNG не поддерживается в IE6. Если вы оптимизируете свой сайт под такую древность — придется применять другие методы или скрипты.
- При отключении отображения картинок, ваш фон пропадет (учтите этот момент при оптимизации отображения на мобильных устройствах, ведь безлимитный интернет не всегда есть под рукою).
- Для изменения цвета и/или степени прозрачности вам нужно создать новую картинку и перезалить ее на серв.
Формат системы RGBA
Одним из самых современных методов изменения транспарантности фона является применение системы RGBA.
RGBA – система представления цвета при помощи трех стандартных каналов RGB (красный, зеленый, синий), и четвертого, так называемого Alpha-канала, характеризующего степень прозрачности.
В уже известном нам примере, заменим содержимое в CSS файле на следующее:
body background: url(./vaden-pro-logo.png); /* Фоновый рисунок */ > .prozrachen padding: 10px; background: rgba(0, 206, 209, 0.7); margin: 0 auto; width: 50%; font: 48px/64px Times New Roman; color: white; text-align: justify; >
- В отличии от свойства opacity прозрачность задается только фону
- В отличии от метода PNG картинки, для изменения цвета или степени транспарентности нам нужно просто поменять значения rgba.
- Кросс-браузерность. Работает во всех современных браузерах (начиная с IE9, Op10, Fx3,Sf3.2).Для более старых браузеров придется либо пожертвовать прозрачностью, либо применять opacity, png методы.
Клетчатые изображения, или с уважением к истории
Этот метод стоял у истоков веб-дизайна, и видел старые-старые браузеры, которые ничего толком не умели. Он заключается в создании клетчатого фона, в котором цветные квадратики чередовались с прозрачными.
В результате применения такой картинки в качестве background получали псевдо-прозрачный фон.
- При просмотре текста на таком фоне могут быстро уставать глаза (особенно давит рябь при прокрутке).
- В остальном особенности применения аналогичны с методом «PNG -картинки».
Подытожим?
Напоследок, несколько общих рекомендаций по использованию прозрачности в своих проектах:
- Под прозрачным блоком должна находиться яркая не однообразная картинка. На однотонном фоне изюминка прозрачности теряется.
- При выборе конкретного практического подхода, ориентируйтесь на то, какими браузерами пользуется ваша целевая аудитория. Кросс-браузерность — вещь важная.