- opacity
- Try it
- Syntax
- Values
- Description
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Setting opacity
- HTML
- CSS
- Result
- Setting opacity on hover
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS Colors
- RGBA Colors
- Example
- HSL Colors
- Example
- HSLA Colors
- Example
- Opacity
- CSS прозрачность (Opacity vs RGBA)
- CSS прозрачность Opacity
- Прозрачность через CSS Opacity
- CSS прозрачность в формате RGBA
- Результат примера с RGBA:
- Вывод
- Комментарии ( 2 ):
opacity
The opacity CSS property sets the opacity of an element. Opacity is the degree to which content behind an element is hidden, and is the opposite of transparency.
Try it
Syntax
opacity: 0.9; opacity: 90%; /* Global values */ opacity: inherit; opacity: initial; opacity: revert; opacity: revert-layer; opacity: unset;
Values
Value | Meaning |
---|---|
0 | The element is fully transparent (that is, invisible). |
Any strictly between 0 and 1 | The element is translucent (that is, content behind the element can be seen). |
1 (default value) | The element is fully opaque (visually solid). |
Description
opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element’s background, even if they have different opacities relative to one another.
Using opacity with a value other than 1 places the element in a new stacking context.
To change the opacity of a background only, use the background property with a color value that allows for an alpha channel. For example:
Accessibility concerns
If text opacity is adjusted, it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over 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 luminosity of the opacity-adjusted 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
Initial value | 1 |
---|---|
Applies to | all elements |
Inherited | no |
Percentages | map to the range [0,1] |
Computed value | The same as the specified value after clipping the to the range [0.0, 1.0]. |
Animation type | by computed value type |
Formal syntax
Examples
Setting opacity
The following example demonstrates how the opacity property changes the opacity of the entire element and content, thus making the text very hard to read.
HTML
div class="light">You can barely see this.div> div class="medium">This is easier to see.div> div class="heavy">This is very easy to see.div>
CSS
div background-color: yellow; font-weight: bold; font-size: 130%; > .light opacity: 0.2; /* Barely see the text over the background */ > .medium opacity: 0.5; /* See the text more clearly over the background */ > .heavy opacity: 0.9; /* See the text very clearly over the background */ >
Result
Setting opacity on hover
In the following example opacity is changed on hover, so the striped background image on the parent element shows through the image.
HTML
div class="wrapper"> img src="//interactive-examples.mdn.mozilla.net/media/dino.svg" alt="MDN Dino" width="128" height="146" class="opacity" /> div>
CSS
img.opacity opacity: 1; > img.opacity:hover opacity: 0.5; > .wrapper width: 200px; height: 160px; background-color: #f03cc3; background-image: linear-gradient( 90deg, transparent 50%, rgba(255, 255, 255, 0.5) 50% ); background-size: 20px 20px; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
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.
CSS Colors
CSS supports 140+ color names, HEX values, RGB values, RGBA values, HSL values, HSLA values, and opacity.
RGBA Colors
RGBA color values are an extension of RGB color values with an alpha channel — which specifies the opacity for a color.
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).
The following example defines different RGBA colors:
Example
HSL Colors
HSL stands for Hue, Saturation and Lightness.
An HSL color value is specified with: hsl(hue, saturation, lightness).
- Hue is a degree on the color wheel (from 0 to 360):
- 0 (or 360) is red
- 120 is green
- 240 is blue
- Saturation is a percentage value: 100% is the full color.
- Lightness is also a percentage; 0% is dark (black) and 100% is white.
The following example defines different HSL colors:
Example
HSLA Colors
HSLA color values are an extension of HSL color values with an alpha channel — which specifies the opacity for a color.
An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the alpha parameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
The following example defines different HSLA colors:
Example
Opacity
The CSS opacity property sets the opacity for the whole element (both background color and text will be opaque/transparent).
The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Notice that the text above will also be transparent/opaque!
The following example shows different elements with opacity:
CSS прозрачность (Opacity vs RGBA)
На этом уроке мы с вами разберем такие CSS свойства – opacity и RGBA. Свойство Opacity отвечает только за прозрачность элементов, а функция RGBA – за цвет и прозрачность, если указать значение прозрачности альфа-канала.
CSS прозрачность Opacity
Цифровое значение для opacity задано в пределах от 0.0 до 1.0, где ноль это полная прозрачность, а единица наоборот — абсолютная непрозрачность. Например, для того, чтобы увидеть 50% прозрачности, надо выставить значение в 0.5. Надо иметь ввиду, что opacity распространяется на все дочерние элементы родителя. А это значит, что и текст на полупрозрачном фоне, тоже будет полупрозрачным. А это уже очень существенный недостаток, текст не так хорошо выделяется.
Прозрачность через CSS Opacity
На скриншоте отчётливо видно, что черный текст стал таким же полупрозрачным, как и голубой фон.
div background: url(images/yourimage.jpg); /* Фон картинка */
width: 750px;
height: 100px;
margin: auto;
>
.blue background: #027ав4; /* Цвет полупрозрачного фона */
opacity: 0.3; /* Значение полупрозрачности фона */
height: 70px;
>
h1 padding: 6px;
font-family: Arial Black;
font-weight: bolder;
font-size: 50px;
>
CSS прозрачность в формате RGBA
Формат для записи цвета RGBA, является более современной альтернативой для свойства opacity. R (red), G (green), B(blue) – значит : красный, зеленый, синий. Последняя буква A – означает альфа-канал, который и задает прозрачность. RGBA в отличии от Opacity не влияет на дочерние элементы.
Теперь давайте рассмотрим наш пример с использованием RGBA. Заменим эти строчки в стилях.
background: ##027ав4; /* Цвет фона */
opacity: 0.3; /* значение полупрозрачности фона */
background: rgba(2, 127, 212, 0.3);
Как вы видите значение прозрачности 0.3 совпадает у обоих методов.
Результат примера с RGBA:
Второй скриншот намного лучше смотрится, чем первый.
Играясь с полупрозрачностью фона блоков, можно добиться на сайте интересных эффектов. Важно, чтобы эти полупрозрачные блоки шли поверх пестрого рисунка, например фотографии. Только в этом случае эффект будет заметен. Этот прием уже давно применялся в дизайне, ещё до появления всяких CSS3, реализовывался он чисто в графических программах.
Если заказчик требует, чтобы верстка хорошо смотрелась и в старых версиях браузера Internet Explorer, тогда добавляйте свойство filter и не забудьте закомментировать, чтобы не пострадала валидность кода.
Вывод
Формат RGBA поддерживают все современные браузеры, за исключением Internet Explorer. Ещё очень важно, что RGBA гибок, он действует только на конкретный заданный элемент, не затрагивая дочерних. Понятно, что для верстальщика это удобнее. Мой выбор однозначно в пользу формата RGBA для получения прозрачности в CSS.
Для лучшего закрепления материала и большей наглядности, предлагаю вам пройти мой видео-курс.
Создано 01.02.2018 09:22:30
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 2 ):
спасибо за полезную статью.
А возможно ли сделать для IE текст прозрачный, но оставить тень от текста? У меня в IE11 становится прозрачным и текст и тень.
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.