Css overlay div with image

How to Overlay Images with CSS

Overlays can be a great addition to the image and create an attractive website. In this snippet, we’ll show different ways of using overlays in CSS.

A common method is to use a colored overlay over a linked image. First, we’re going to demonstrate an example where we slightly darken the image. Let’s start with creating HTML.

Create HTML

h1>Example h1> h2>Original image h2> div class="image"> div> h2>Overlay image h2> div class="image"> div class="overlay"> div> div>

Add CSS

  • Set the width, height, and background-color for the “overlay” class.
  • Specify the background-image and other background properties for the «image» class.
h1 < text-align: center; > .overlay < width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); > .image < width: 500px; height: 330px; margin-bottom: 20px; background-image: url('https://images.unsplash.com/photo-1538367999111-0d6c7fb0299f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'); background-position: center; background-size: cover; background-repeat: no-repeat; >

Now, you can see the full example.

Example of overlaying an image:

html> html> head> title>Title of the document title> style> h1 < text-align: center; > .overlay < width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); > .image < width: 500px; height: 330px; margin-bottom: 20px; background-image: url('https://images.unsplash.com/photo-1538367999111-0d6c7fb0299f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'); background-position: center; background-size: cover; background-repeat: no-repeat; > style> head> body> h1>Example h1> h2>Original image h2> div class="image"> div> h2>Overlay image h2> div class="image"> div class="overlay"> div> div> body> html>

Result

We can also add hover effects to the linked images. Color overlays are the most common effect that can be added to the website and create hover effects. Let’s see some examples and learn how to create an overlay effect on the image on hover.

Читайте также:  Javascript window location new url

Example of overlaying an image on hover:

html> html> head> style> .container < position: relative; width: 50%; > .image < display: block; width: 100%; height: auto; > .overlay < position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .7s ease; background-color: #339c57; > .container:hover .overlay < opacity: 1; > .text < color: white; font-size: 18px; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; > style> head> body> div class="container"> img src="https://images.unsplash.com/photo-1583528306385-8f29f27cb2d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="travel" class="image"> div class="overlay"> div class="text">Travel div> div> div> body> html>

Example of overlaying an image on hover with a fading effect:

html> html> head> title>Title of the document title> style> .container < position: relative; width: 50%; > .image < opacity: 1; display: block; width: 100%; height: auto; transition: .7s ease; backface-visibility: hidden; > .middle < transition: .7s ease; opacity: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; > .container:hover .image < opacity: 0.4; > .container:hover .middle < opacity: 1; > .text < background-color: #009c36; color: white; font-size: 18px; padding: 14px 28px; > style> head> body> div class="container"> img src="https://images.unsplash.com/photo-1583528306385-8f29f27cb2d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="travel" class="image"> div class="middle"> div class="text">Travel div> div> div> body> html>

Example of overlaying an image title:

html> html> head> title>Title of the document title> style> * < box-sizing: border-box; > .container < position: relative; width: 50%; max-width: 300px; > .image < display: block; width: 100%; height: auto; > .overlay < position: absolute; bottom: 0; background: rgb(0, 0, 0); background: rgba(0, 0, 0, 0.5); color: #f1f1f1; width: 100%; transition: .7s ease; opacity: 0; color: white; font-size: 20px; padding: 20px; text-align: center; > .container:hover .overlay < opacity: 1; > style> head> body> div class="container"> img src="https://images.unsplash.com/photo-1583528306385-8f29f27cb2d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="travel" class="image"> div class="overlay">Travelling div> div> body> html>

In our last example, we create the effect of an image overlay using two images, one of them overlaying the other. Our second image will appear at the bottom right corner of the first image when hovering.

Читайте также:  Css template mobile app

Example of overlaying an image with another image:

html> html> head> title>Title of the document title> style> .gallerypic < width: 500px; text-decoration: none; position: relative; display: block; border: 1px solid #666; padding: 3px; margin-right: 5px; float: left; > .gallerypic span.zoom-icon < visibility: hidden; position: absolute; right: 0; bottom: 0; filter: alpha(opacity=50); -moz-opacity: 0.5; -khtml-opacity: 0.5; opacity: 0.6; > a.gallerypic:hover span.zoom-icon < visibility: visible; > style> head> body> a href="#" class="gallerypic"> img src="https://images.unsplash.com/photo-1492136344046-866c85e0bf04?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="Gallery Photo" class="pic" /> span class="zoom-icon"> img src="https://images.unsplash.com/photo-1505205296326-2178af1b47bf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" width="200" height="150" alt="Zoom"> span> a> body> html>

Источник

Способы создания перекрывающего слоя overlay

Overlay (оверлей), или перекрывающий слой — это слой, который обычно накладывают поверх фонового изображения для того, чтобы затемнить или осветлить его. Дизайнеры в макетах обычно создают его в виде векторного слоя с полупрозрачной заливкой. Цвет заливки зависит от цветов, использованных в макете.

Еще один вариант оверлея используют для создания модальных окон. В этом случае он перекрывает весь контент сайта, а выше него размещается только модальное, или pop-up окно.

В этой статье мы рассмотрим несколько способов создания оверлеев, т.е. перекрывающих слоев, которые закрывают только фоновое изображение. Контент же блока находится поверх оверлея и доступен для чтения, выделения и копирования информации.

Способ 1. Вкладываем перекрывающий слой overlay внутрь контейнера с заданной высотой

Очень часто необходимо добавить перекрывающий слой в такой блок, как header . За счет того, что в этот html-элемент, как правило добавляют большое фоновое изображение, которое собственно и нужно перекрыть слоем overlay, и совсем немного текста, для header обычно явно задают такое свойство, как height . Внутри header в разметке размещают , а уже внутри него — всю остальную разметку.

В CSS-свойствах для header задают height и нужные свойства группы background, а для .overlay — padding , height: 100% и нужный цвет фона с полупрозрачностью в системе rgba() или hsla() .

Однако здесь есть один подвох. Учтите, что по умолчанию браузер расчитывает ширину и высоту только для контента — за это отвечает свойство box-sizing со значением content-box . Поэтому, как только вы зададите padding-top или padding-bottom , в том числе и в виде свойства padding: 10px 0 , для любого элемента с явно указанной высотой хоть в виде height: 500px , хоть в виде height: 100% , часть этого элемента у вас «вылезет» внизу за пределы родителя, т.к. любые padding добавляются к указанной вами высоте.

Поэтому для того, чтобы высота (да и ширина тоже) считались вместе с внутренними отступами, нужно указывать либо для .overlay свойство box-sizing: border-box , либо делать это для всех элементов с помощью универсального селектора в виде * . Поскольку в примерах ниже мы еще будем использовать и псевдоэлементы ::before и ::after, то имеет смысл сразу же написать это свойство и для них в таком виде:

Источник

Оцените статью