Css overlay with text

Images and text overlays in HTML/CSS

Here is a very simple tutorial to design image overlays in HTML and CSS only.

Indeed, who has never wanted to quickly position a text over an image? Then change it on mouse hover or even display an alternate image?

The code provided in this article may apply to any website. Simply integrate the HTML code on a page and the CSS code into your stylesheet.

You can find different ways to do it on the internet, but I wanted to synthesize everything I found to extract a minimal and above all clean solution.

What is an image text overlay?

For me, an overlay is just a layer put on top of another. In HTML, it means that it is out of the flow, because it has to be positionned over another element, which is not possible with the default behaviour.

Note: I’m not talking here about text over a background image, which is standard in HTML, but text over an image element (the infamous img tag).

Simple text overlay with no hover

Alt text

Overlay with background and text change on hover

Texte alternatif

Overlay with text and image change on hover

Texte alternatif

Texte alternatif hover

HTML code: original content and overlay

Content structure

The overlay-image class container encapsulates all the necessary structure:

  • original image,
  • original overlay text block,
  • image/text overlay block displayed on mouse hover.

On a page written without a page builder (HTML page or simple WordPress theme), for instance like this article, it is essential to define it in order to properly include original content and overlay within the page.

With a builder, it can be replaced by an existing container block (for example it could be the Divi “code” module, to which we simply add the overlay-image class).

The code below also includes encapsulating link tags to make images clickable, but you can remove them if not needed.

The HTML code

CSS code: text overlay and text/image change on hover

The code below is to be included in your styles definition:

  • style.css file included in your HTML file if you work directly in HTML,
  • style.css file of your child theme if you work with WordPress,
  • or your Divi page options if the mechanism is only used at a specific location.

How to display the original or simple text overlay?

The overlay-image class allows you to set the global container when not using a page builder. In this article, I replaced the “width: 100%;” by “width: 80% margin: auto;” to add margins.

Important note: The image-overlay container MUST be “positioned” itself (here relative) in order to position its own elements.

Original image and text overlay are defined by .overlay-image .image and .overlay-image .text specifiers:

  • the image fills all available space,
  • the text is centered on the image using an absolute “positioning” on the container block and a X-Y translation (a CSS classic).

How to display the new overlay on hover?

The hover overlay is materialized by .overlay-image .hover, and “positioned” in absolute to occupy the entire surface of the container including original image and text (100% width and height).

When the mouse hovers, its opacity changes from 0 to 1 with a smooth transition to make it appear over the original div.

To overlay a text block only (without image), you must first hide the original text because the new image is not there to do so.

The CSS code

I tried to factorize the code to make it simple, readable, compact and easily usable. To do so, I divided it into three parts that you can pick according to your needs.

The first part is common to all three kinds of previous overlays and this is the only one needed for a simple text overlay:

/********* Simple or original overlay *******/ /* Main container */ .overlay-image < position: relative; width: 100%; >/* Original image */ .overlay-image .image < display: block; width: 100%; height: auto; >/* Original text overlay */ .overlay-image .text

This part is needed by both overlays on hover:

/********* Overlay on hover *******/ /* New overlay on hover */ .overlay-image .hover < position: absolute; top: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ease; >/* New overlay appearance on hover */ .overlay-image:hover .hover

This last part in only needed for background + text overlay on hover:

/********* Background and text only overlay on hover *******/ .overlay-image .normal < transition: .5s ease; >.overlay-image:hover .normal < opacity: 0; >.overlay-image .hover

Conclusion

As you can see, overlays are not technically very difficult… It’s a shame that the mechanism is not part of all WordPress themes on the marketplace!

46 commentaires sur cet article

Thank you SO MUCH for providing this tutorial. I have been searching for hours and all of the other tutorials I found made it way too complicated. Yours is straightforward and very helpful.

You’re welcome, glad it could help!

Hello, Can anybody help me to change font-color to black on mouseover? Thank you!

Hi Lidiya, You can try this: .overlay-image .hover .text

Thank you very much for this really simple and super useful code! I used it, with a lot of ccs modifications, in many of my Joomla sites

Awesome! I’m glad it was so usefull 🙂

Thank you so much for this tutorial. How to put background color on image and on hover to image background color should be removed Thanks!!

Hi, You can add a background color with transparency on the “normal” overlay-image, with opacity 1, and set opacity to 0 on the “hover” overlay-image.

Hi! Thank you so much for this tutorial. 🙂 I was just wondering – would this be possible to accomplish using only HTML? Thanks!

Hi Andy, Do you mean without CSS? If so, the answer is no. But you can inline the CSS in HTML tags if you don’t want external CSS (using style=”…” instead of classes). Hope it can help!

How can I use that with Owl Carousele plugin? I need 4 divs, with inside foto+text in each slide.

Hi Den, Honestly I don’t use Owl Caroussel so I can’t tell you precisely. But if you can insert HTML in slides, you can try and use this code with the CSS in your style.css.

Excellent tutorial. Thanks for share your knowledge!

Thank you for your message 🙂

Thanks for this useful content. It’s always a pleasure to read your great posts filled with tips really!

You’re welcome, and thx for your message!

Thank you SO MUCH! I have been looking for several days for something that lays out the whole idea so simply and clearly! This is such a helpful tutorial.

You’re welcome, glad I could help.

Diego Alvarez February 6, 2019

Источник

Как создать эффект наложения с помощью CSS

Есть несколько способов создания наложений. В этой статье мы покажем, как создать наложение с помощью CSS свойств.

Один из способов создания такого эффекта является абсолютное позиционирование HTML элемента на странице. Необходимо в разметке создать div, потом абсолютно позиционировать его с помощью свойства position, и дальше с помощью свойства z-index задать для div высокий z-index, чтобы он находился поверх всех остальных элементов страницы. Мы зададим более высокий z-index для следующего элемента div, которое откроется сверху наложения.

Для position задайте значение absolute, а z-index установите в 10.

div >div> div >div> .overlay< position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; >

Здесь мы устанавливаем свойство position в fixed а z-index в 11, на 1px выше, чем слой наложения.

.modal < width: 300px; height: 200px; line-height: 200px; position: fixed; top: 40%; left: 50%; margin-top: -100px; margin-left: -150px; background-color: #8ebf42; border-radius: 40px; text-align: center; z-index: 11; >

Мы устанавливаем position в значение relative.

body< position: relative; padding: 20px; margin:0; min-height:100%; font-family: 'Open Sans', sans-serif; background: #8ebf42; color: #eeeeee; >

И так, мы создали наложение. Давайте посмотрим результат!

Пример

html> html> head> title>overlay div title> style> body< position: relative; padding: 20px; margin:0; min-height:100%; font-family: 'Open Sans', sans-serif; background: #8ebf42; color: #eeeeee; > .overlay < position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; background-color: rgba(0,0,0,0.6); > .modal < width: 300px; height: 200px; line-height: 200px; position: fixed; top: 40%; left: 50%; margin-top: -100px; margin-left: -150px; background-color: #8ebf42; border-radius: 40px; text-align: center; z-index: 11; > style> head> body> h2>Создание наложения с абсолютно позиционированным элементом h2> div class="overlay"> div> div class="modal">Lorem Ipsum - это текст-"рыба" div> div>Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum. div> body> html>

Мы также можем создать наложение при помощи селекторов ::before и ::after.

Стили и решения этого метода во многом похожи на предыдущий. Только здесь необходимо добавить стиль к псевдоклассам ::before и ::after .

Пример

html> html> head> title>overlay div title> style> body< position: relative; padding: 20px; margin:0; min-height:100%; font-family: 'Open Sans', sans-serif; background: #8ebf42; color: #eeeeee; > body :after < content: ""; display: block; position: fixed; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; background-color: rgba(0,0,0,0.3); > .modal < width: 300px; height: 200px; line-height: 200px; position: fixed; top: 40%; left: 50%; margin-top: -100px; margin-left: -150px; background-color: #8ebf42; border-radius: 40px; text-align: center; z-index: 11; > style> head> body> h2>Создание наложения с абсолютно позиционированным элементом h2> div class="modal">Lorem Ipsum - это текст-"рыба" div> div>Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum.Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов. Lorem Ipsum не только успешно пережил без заметных изменений пять веков, но и перешагнул в электронный дизайн. Его популяризации в новое время послужили публикация листов Letraset с образцами Lorem Ipsum в 60-х годах и, в более недавнее время, программы электронной вёрстки типа Aldus PageMaker, в шаблонах которых используется Lorem Ipsum. div> body> html>

Источник

Читайте также:  Html автоматически по колонкам
Оцените статью