- opacity
- Кратко
- Пример
- Как пишется
- Как понять
- Подсказки
- На практике
- Алёна Батицкая советует
- 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
- Transparent Text Background Image In HTML CSS (Simple Examples)
- QUICK SLIDES
- TABLE OF CONTENTS
- DOWNLOAD & NOTES
- QUICK NOTES
- EXAMPLE CODE DOWNLOAD
- TRANSPARENT HTML ELEMENTS
- 1) TRANSPARENT TEXT
- 2) TRANSPARENT BACKGROUND
- 3) TRANSPARENT IMAGE
- USEFUL BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
opacity
Прячем элемент на странице, делая его полностью или частично прозрачным.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Свойство opacity управляет прозрачностью элемента. С его помощью можно полностью спрятать текст или элемент. А можно сделать полупрозрачным — дизайнеры любят такой приём на современных сайтах.
Пример
Скопировать ссылку «Пример» Скопировано
Элемент станет прозрачным:
.selector opacity: 0;>
.selector opacity: 0; >
Элемент полупрозрачный, сквозь него видно фон:
.selector opacity: 0.5;>
.selector opacity: 0.5; >
Элемент совсем непрозрачный:
.selector opacity: 1;>
.selector opacity: 1; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Свойство opacity принимает дробные или целые значения от 0 до 1 включительно. 0 будет означать полную прозрачность, а 1 полную непрозрачность (значение по умолчанию).
Как понять
Скопировать ссылку «Как понять» Скопировано
Можно представить, что 0 равен 0% видимости элемента, а 1 в свою очередь 100% видимости элемента. Указывая любые промежуточные значения вы гибко управляете видимостью.
Стоит быть внимательным с этим свойством: невидимый элемент всё равно остаётся на странице и продолжает влиять на поток документа. Грубо говоря, если вы скроете какой-то блок при помощи opacity , то он просто будет невидим, но не перестанет занимать своё место, его соседи не займут его место, а родитель не схлопнется, если это был единственный ребёнок.
Представьте, что элемент просто надевает Мантию-невидимку как у Гарри Поттера.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Свойство прозрачности можно анимировать 🎉
💡 Элемент не пропадает со страницы, продолжает влиять на поток документа.
💡 Можно задавать любые дробные значения. Например, 0.33 или 0.1.
💡 Это не наследуемое свойство. НО! Если родителю задано это свойство, то и все дети вместе с ним будут становиться прозрачными.
💡 Вместо opacity : 0 можно использовать свойство visibility : visibility : hidden — будет тот же результат.
💡 В дробных значениях можно опустить первый ноль: opacity : . 5 . И всё равно будет работать 🧙♀️
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 Очень частый кейс — сделать полупрозрачную заливку поверх картинки. Это обычно называют оверлеем или вуалью. В этом случае не стоит применять свойство opacity , работайте с полупрозрачными цветами с альфа-каналом.
selector position: relative;> selector:before content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgb(0 0 0 / 0.5); /* или в формате HEX background-color: #00000080; */>
selector position: relative; > selector:before content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgb(0 0 0 / 0.5); /* или в формате HEX background-color: #00000080; */ >
🛠 Когда-то была популярна шутка, что если ваш заказчик не заплатил вам, то его можно шантажировать следующим способом: цепляете на сайт скрипт, который будет каждый день уменьшать opacity для body на 0.1 пока сайт полностью не пропадёт или пока заказчик не заплатит 😬
Если что, это не я вам рассказала 🤫
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.
Transparent Text Background Image In HTML CSS (Simple Examples)
Welcome to a quick tutorial and examples on how to create transparent text, background, and images in HTML CSS. Once upon a time in the Dark Ages of the Internet, we have to manually create GIF or PNG images to do transparency. Today, things are very easy to modern CSS.
- To create transparent text, simply define the color with rgba . For example, p.ghost < color: rgba(0, 0, 0, 0.5); >
- To create a transparent background, we set the background using rgba . For example, div.ghost < background: rgba(0, 0, 0, 0.5); >
- Lastly, we can create transparent images and just about any transparent element using opacity . For example, img.ghost
That covers the quick basics, but read on for more examples!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
TRANSPARENT HTML ELEMENTS
All right, let us now get into the examples of how to create transparent elements in HTML and CSS.
1) TRANSPARENT TEXT
- RGB stands for the basic colors – red, green, blue.
- A stands for alpha, or “transparency” in layman terms.
- So how this works is very simple, we mix and match RGB (a number from 0 to 255) to get different colors. Then, the alpha is a number from 0 (invisible) to 1 (opaque).
2) TRANSPARENT BACKGROUND
Yep, it’s the same rgba here. Except that we define it to the background instead.
3) TRANSPARENT IMAGE
Lastly, we can use opacity to change the transparency of almost any HTML element. Some of you smart code ninjas may be thinking that background-image makes more sense here – But no. As at the time of writing, there is no such thing as background-opacity . So it’s back to the old-school way of layering elements to create the transparent background image.
USEFUL BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.