Transparent Background – Image Opacity in CSS and HTML

Kolade Chris

Transparency plays an important role in front end development. It lets you choose how transparent the elements on your web pages appear.
You can adjust transparency in several ways – because of course, in CSS, there are multiple ways to do the same thing.
The CSS opacity property is the first way that might come to your mind to change transparency. But this property can’t come to the rescue all the time, especially when there is a background image with text in it that you want to make transparent.
So in this article, I’m going to show you the various ways you can adjust transparency so you can start implementing it in your coding projects.
Image Transparency with the CSS Opacity Property
To make an image transparent, you can use the CSS opacity property, as I mentioned above. The basic syntax of the opacity property is shown in the code snippet below:
The opacity property takes values from 0.0 to 1.0 , with 1 being the default value for all elements. The lower the value, the more transparent. So if an element is given an opacity of 0 , it would be invisible.
You can find examples of different opacity values in the code snippets below:
I have added some CSS to center everything on the page:

An opacity value of 1 is the default, so the image appears like this:
This code gives us 50% opacity, and you can see that the logo has faded a bit:

With an opacity of 0 , the image is 100% transparent, so it becomes invisible:

The only way to be sure the image is on the page is to inspect it with your browser devtools:

You can use this opacity value to do a lot of things – for example, you can use it to include text over a hero image on a website.
You might be wondering why you would want to make content invisible with an opacity value of 0. Well, it can be useful in animations, and in building HTM + CSS + JavaScript games as well.
You’ll definitely want to use CSS positioning to help you align things. I’ll discuss this in the next parts of the article.
Background Image Transparency in HTML and CSS
CSS offers a way to set the background image for a container element with the background-image property, so you don’t necessarily have to do it with the CSS. This means you can also place text in the container as well.
The downside of this approach is that the opacity is set for the container where the image and text are. So, the opacity affects the text as well, not only the image. This is probably not what you want!

The solution
By default, when you apply an opacity to a container, the descendants inherit it as well.
A workaround in this situation is to set the background image in the HTML. This makes it easy to apply the opacity to the image only, instead of setting the background image for the container in the CSS.
This time around, the image and the text will be separated, so the text will not inherit the value set for the opacity .
This means you also have to use CSS positioning to align the text within the image.
In the CSS code snippet above, I use flexbox to center everything on the page.
The container div element with the class of showcase is positioned relative , so you can position the h1 text absolute within it. This will push the h1 text to the top-left corner of the image. The top and left properties are then used to push the text to the bottom-left corner of the image.
If you are wondering what the top and left properties are, they are the properties you get access to when you use the display property.
In addition to these two, you also get access to the right and bottom properties. They let you position an element anywhere.

In the end, the image is opaque and the text is not affected:
Conclusion
In this article, you learned how to use the opacity property of CSS to make images transparent.
As CSS remains tricky and a bit weird, it’s helpful to combine the opacity property with other CSS features such as positioning in order to put it into proper use.
Apart from CSS positioning, you can also use the opacity property with CSS pseudo-elements such as ::before and ::after , which is sort of a hacky way of doing things.
How to insert image with transparent background, in HTML?
but when I open the page (through chrome) the background color is white, and I don’t want it white, I want it to be transparent.
I would like not to use CSS, but if there is no other option so I’ll do it.
1 Answer 1
Please note that, if you are not giving any colours for the background, then by default it will be white on most browsers! If you are using chrome, you can do like this:
As said in the comment by KittMedia, if you are targetting new browsers, replace transparent with:
This way, you can overlay two images and keep them transparent too. Is this what you are expecting?
Способы создания прозрачных фонов
Вы хотите научиться создавать страницы с оригинальным и ярким современным дизайном? Применение полупрозрачных элементов способно помочь Вам в решении этой непростой задачи. Сегодня мы рассмотрим основные практические способы задания прозрачности структурных элементов.

Как задать прозрачность?
Если рассматривать данную тему сквозь призму исторического развития веб-технологий, то можно выделить следующие подходы:
- Свойство opacity.
- Использование PNG -картинки
- Формат системы RGBA
- Ну, и наконец, древность или клетчатые изображения.
CSS свойство Opacity
Применение стилевого CSS свойства оpacity позволяет задать прозрачность того элемента, к которому применяется. Значения, которые можно использовать в качестве аргумента изменяются в пределах от 0 до 1.
Рассмотрим пример.
В результате мы получили полупрозрачный блок:

- Opacity принимает значения из диапазона: 0 (полная прозрачность) — 1 (непрозрачность).
- Кросс-браузерность. В IE до седьмой версии включительно Opacity не поддерживается. Добиться одинакового отображения элемента поможет следующая строчка:
Стоит принимать во внимание то, что свойство filter отсутствует в html спецификациях, изменяет значения от 1 до 100 и может применяться только к элементам:
- с абсолютным позиционированием (position: absolute)
- с фиксированным линейным размером (height или width).
Для лучшего понимания материала последнего пункта, в предыдущем примере зададим тексту белый цвет
и рассмотрим его под микроскопом:

Как видим, контент нашего блока (текст) тоже стал полупрозрачным. Но что делать, если на практике прозрачность содержимого вас не интересует, а интересует лишь прозрачность фона? В таком случае, переходим к следующему пункту.
Использование PNG -картинки
Интересной особенностью формата PNG является то, что он имеет 256 уровней прозрачности. Думаю, Вы уловили ход мыслей, и наверняка уже построили алгоритм работы такого подхода. Мне остается только его озвучить.
-
Создаем в Photoshop, однотонную полупрозрачную картинку (назовем ее transparent) и сохраняем в формате png.

В результате мы получили блок с прозрачным фоном и непрозрачным содержимым:

- В отличии от свойства opacity прозрачность задается только для фона
- Кросс-браузерность. Работает почти во всех браузерах, и это плюс. Но прозрачность PNG не поддерживается в IE6. Если вы оптимизируете свой сайт под такую древность — придется применять другие методы или скрипты.
- При отключении отображения картинок, ваш фон пропадет (учтите этот момент при оптимизации отображения на мобильных устройствах, ведь безлимитный интернет не всегда есть под рукою).
- Для изменения цвета и/или степени прозрачности вам нужно создать новую картинку и перезалить ее на серв.
Формат системы RGBA
Одним из самых современных методов изменения транспарантности фона является применение системы RGBA.
RGBA – система представления цвета при помощи трех стандартных каналов RGB (красный, зеленый, синий), и четвертого, так называемого Alpha-канала, характеризующего степень прозрачности.
В уже известном нам примере, заменим содержимое в CSS файле на следующее:

- В отличии от свойства opacity прозрачность задается только фону
- В отличии от метода PNG картинки, для изменения цвета или степени транспарентности нам нужно просто поменять значения rgba.
- Кросс-браузерность. Работает во всех современных браузерах (начиная с IE9, Op10, Fx3,Sf3.2).Для более старых браузеров придется либо пожертвовать прозрачностью, либо применять opacity, png методы.
Клетчатые изображения, или с уважением к истории
Этот метод стоял у истоков веб-дизайна, и видел старые-старые браузеры, которые ничего толком не умели. Он заключается в создании клетчатого фона, в котором цветные квадратики чередовались с прозрачными.

В результате применения такой картинки в качестве background получали псевдо-прозрачный фон.

- При просмотре текста на таком фоне могут быстро уставать глаза (особенно давит рябь при прокрутке).
- В остальном особенности применения аналогичны с методом «PNG -картинки».
Подытожим?
Напоследок, несколько общих рекомендаций по использованию прозрачности в своих проектах:
Как сделать задний фон картинки прозрачным html?
>
#pc <
display: none;
>
#mobile <
display: inline-block;
>
>
.header <
border: none;
border-bottom: 2px solid white;
position: fixed;
width: 100%;
height: 10%;
right: 0;
top: 0;
background: #34e89e; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #0f3443, #34e89e); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #0f3443, #34e89e); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
>
.content <
position: absolute;
right: 0;
bottom: 0;
width: 100%;
height: 90%;
background: #C33764; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #1D2671, #C33764); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #1D2671, #C33764); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
>
media screen and (orientation : landscape) <
#pc <
display: inline-block;
>
#mobile <
display: none;
>
.header <
border: none;
border-bottom: 2px solid white;
>
.header__text <
position: fixed;
margin-left: 10px;
>
>
.header__text <
position: fixed;
top: 0;
width: 100%;
height: 100%;
>
media screen and (orientation: landscape) <
.simple <
margin-top: 0.5%;
margin-left: 6%;
>
.pop <
margin-top: 0.5%;
margin-left: 4%;
float: left;
>
>
media screen and (orientation: portrait) <
.simple <
position: absolute;
margin-top: 3%;
margin-left: 10%;
>
.pop <
margin-top: 3%;
margin-left: 4%;
float: left;
>
>
.simple,.pop <
border-radius: 5px;
border: 2px solid white;
>.about <
background: #C33764; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #1D2671, #C33764); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #1D2671, #C33764); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
>
body <
background: #C33764; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #1D2671, #C33764); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #1D2671, #C33764); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
>