Как добавить оверлей (затемнение) на фоновое изображение
Оверлей (затемнение) на фоновом изображении используется для улучшения читаемости текста или создания определенного настроения на веб-странице. В этой статье мы рассмотрим, как добавить оверлей на фоновое изображение с помощью CSS.
Способ 1: Использование псевдоэлемента
Один из способов добавить оверлей на фоновое изображение – использовать псевдоэлемент ::before или ::after . В этом случае создается «виртуальный» элемент, который накладывается поверх фонового изображения и затемняет его.
.image-with-overlay < position: relative; background-image: url('path/to/your/image.jpg'); background-size: cover; background-position: center; >.image-with-overlay::before < content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); /* Здесь можно изменить цвет и степень затемнения */ z-index: 1; >.image-with-overlay > *
В этом примере мы создаем псевдоэлемент ::before , задаем ему абсолютное позиционирование и полупрозрачный черный фон. Текстовый контент внутри блока получает больший z-index для отображения поверх оверлея.
Способ 2: Использование линейного градиента
Еще один способ добавить оверлей на фоновое изображение – использовать линейный градиент в свойстве background-image вместе с самим изображением. В этом случае оверлей создается непосредственно в фоне элемента.
Здесь мы используем линейный градиент с двумя одинаковыми полупрозрачными цветами, что создает равномерный оверлей поверх изображения.
Теперь вы знаете два способа добавления оверлея на фоновое изображение с помощью CSS! 😊 Не забывайте экспериментировать с цветами и степенью затемнения для создания уникального вида вашего сайта.
Очень часто я стал видеть на сайтах затемнение фона. Особенно часто это делается в галереях, где по клику на изображение, оно увеличивается, а вся остальная часть затемняется. Безусловно, практически везде стоит специальный плагин JQuery, но в этой статье я расскажу, как сделать затемнение фона через CSS, не прибегая к JQuery.
Давайте напишу HTML-код:
Здесь я добавил одну таблицу, в качестве тестового контента, который будет затемнён. А также блок TB_overlay, который и является ключевым, то есть он будет затемнять. Привожу CSS-код:
#TB_overlay background-color: #000; /* Чёрный фон */ height: 100%; /* Высота максимальна */ left: 0; /* Нулевой отступ слева */ opacity: 0.50; /* Степень прозрачности */ position: fixed; /* Фиксированное положение */ top: 0; /* Нулевой отступ сверху */ width: 100%; /* Ширина максимальна */ z-index: 100; /* Заведомо быть НАД другими элементами */ >
Здесь я постарался прокомментировать, но обратите внимание на свойство opacity. Чем выше значение, тем более сильное затемнение. Максимальное значение 1. Фактически, данный способ затемнения фона через CSS очень прост: идёт наложение на весь контент чёрного блока с определённой прозрачностью.
На мой взгляд, данный способ затемнения очень простой и понятный, поэтому он и применяется чаще всего.
Создано 08.02.2012 16:17:12
Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov. Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте, то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Кнопка: Она выглядит вот так:
Текстовая ссылка: Она выглядит вот так: Как создать свой сайт
BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 8 ):
Добрый вечер, Михаил. Я скопировала код, но появилась только таблица, без всякого затемнения. Почему?
Попробуйте в других браузерах, если не получится, значит, как-то не так подключили стили.
Михаил, добрый день. Я новичок, и учусь писать ХТМЛ странички. Есть такой вот код, наверное он даже вашего производства:
Пояснения
X
Здесь на месте этого текста ставьте свой текст или html код.
Подскажите пожалуйста, как интегрировать сюда затемнение, чтобы при открытии модального окна все затемнялось кроме самого окна. Перепробовал кучу вариантов с вашим кодом, но получается только затемнение, само окно остается под затемнением
Это убогий код, и он явно не моего производства. Как интегрировать в эту помойку модальное окно — не знаю. Лучше всё написать заново. Если Вы не знаете, как такое написать, то изучайте HTML. Копировать откуда-то чужой да ещё и кривой код — бесполезная затея.
opacity не поддерживается в старых браузерах..так?
Darken image means we are making our image appear in dark mode. The CSS provides different properties for making the image or background image darker. We can use these properties and set their values according to our choice and make our image a darker image. The CSS provides this opportunity for us to make the images darker using three different properties. In this tutorial, we will make our background image darker by utilizing the CSS properties and will show you the darker as well as the original image.
Properties for Darken Background Image in CSS:
We will use the following three properties which the CSS provides to darken the background image. These properties are:
Using filter property.
Using background-image property and set its value in linear gradient.
Using background-blend-mode property.
Now, we are going to utilize all these properties in our codes below and you will learn from these examples how to use these properties and how to set the value of these properties because we will also explain all codes.
Example # 1:
We’re utilizing Visual Studio Code to show the examples provided. So, we’ll open the new file and select the “HTML” language, which will result in the production of an HTML file. Then, in the newly generated file, we start writing the code. The “.html” file extension is automatically appended to the file name when we save the completed code. Now, we get basic tags by putting “!” marks and pressing “Enter”. When the basic HTML tags have appeared in this file created, we’ll begin by adding a heading.
Then, we also put a paragraph below this heading and insert the image after this paragraph. If the image is inserted, we have another paragraph and also a div class with the name “darkened-image”. Here, the HTML code is completed. Now, save it and let’s move to the CSS file where we will add the “filter” property for darkening the background image.
For “h1”, we set the “font-family” value to “Algerian” and also apply “color” to this heading as “green”. The “font-size” of the paragraph text is “20px” and its “color” is “red”, “bold” in its “font-weight”. Then, we are going to utilize the “filter” property for the div class “darkened-image”. This property helps in making the image darker. We used this property here so the image will appear darker in the output. We set its value using the “brightness” value and select “60%” brightness for this image.
In the “background-image”, we put the same path of the image which we have given in the HTML file. So, we apply this darkened property to the image which we have inserted above and we will see that original image as well as the darkened image on the output screen. We also set the “width” and “height” of the div as “200px” and “620px” respectively. This “height” property will set the height of the div and the “width” property will set the width of the div.
We make this image a darker image with the help of the CSS “filter” property and setting the “brightness” as the value of this property. We have applied “60%” brightness to this image to make it darker than the original image.
Example # 2:
We have a heading here and then add the image. After this image, we again place a heading and then we have a div container. We will utilize the second property for making this image a darker.
We apply “color” to this heading as “maroon” and set the “font-family” value for “h1” to “Algerian”. The “height” of the image is set to “240px” and its “width” is “630px”. Then, we mention the div container “darkened-image” and put the “background-image” property in which we utilize the “linear-gradient” and set its value in “rgba” form. Here, we use two “rgba” values and set them to “rgba(0, 0, 0, 0.5)” where “0.5” is the alpha value. We also insert the image in the “url ()”. We insert the path of the image in this “url ()”. The “height” of this div is “240px” and also, we define its “width” to “630px”.
In the output, both the original and the darkened versions of the image can be seen. The original image and the darkened image may clearly be distinguished from one another in the screenshot below. The darkened image is rendered because we have utilized the “background-image” property and set its value in the “linear-gradient” type.
Example # 3:
We have used the above HTML code and we insert another image in this code. We will use the “background-blend-mode” for creating the darkened image effect on the image.
We set the “font-family” value for “h1” to “Algerian” and apply “color” to this heading to “maroon”. The image’s “width” is “630px” and its “height” is “250px”. We utilize the div class name as “darkened-image” and are going to apply some properties to it. We utilize the “background” property and place the “rgba” value here. The “rgba” value we are utilizing is “(0, 0, 0, 0.7)” and then we have the “url” property which we utilize for giving the path of the image. We give the image’s path as “myNewImage.PNG”.
After this, we have the “background-repeat” property and utilize the “no-repeat” keyword as the value of this property. Now, we also set the “background-size” and place “cover” so the image covers all the background. The “background-blend-mode” property is for applying the darkening effect to the image. We set it as the “darken” keyword. So, when this image renders on the output screen, it will appear as a darkened image because of this property. The “height” of the div named “darkened-image” is adjusted to “330px” and we also set its “width” which is “650px”. Now, look at the output of how these images will appear.
Both the original and the darker forms of the image are visible in the result. Here in the snapshot below, it is possible to easily tell the difference between the original image and the darkened image. We used the “background-blend-mode” attribute and placed the “darker” keyword as the value of this attribute to render the darkened picture.
Conclusion
We have thoroughly covered this concept and looked at numerous instances of how to darken the background image in CSS. As was previously mentioned, we have used three different properties for darkening the background image. We have utilized all three properties in our codes. We also covered how to use these properties and how to set their value. We have discussed that we have the “filter” property, “background-image” property, and also the “background-blend-mode” property for making the background image darker. We also provided the outcomes of all these codes in which we have rendered both the darken as well as the original image on the output screen. For your benefit, we have created a comprehensive tutorial in which the code is both provided and thoroughly explained, along with the results.
About the author
Aqsa Yasin
I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.