Text and background overlay on image

I am trying to create a solid overlay color that exactly matches the size of the image and displays the text on this overlay. I would like to do this only with HTML and CSS, if possible.

image without overlay

image with overlay and text

An image can be of any size and will have a size to fit and center in its parent container. Something like this (which doesn't work):

HTML:

<div class="img-overlay"> <img src="file.jpg"> <div class="overlay">Text will flow...</div> </div> 

CSS

 .img-overlay img { margin: 0 auto; max-height: 100%; } .overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100% background-color: rgba(255,255,255,0.5); } 

I thought the HTML5 <figure> might help here, but didn't have much success on this front. It is indicated below that the width of the title is tied to the width of the image, but when I try to remove it from the document stream and place it on top of the image, it ends to the left of the image due to centering the image using margin: 0 auto; .

 <figure> <img src="file.jpg"> <figcaption>Text will flow...</figcaption> </figure> 
+6
source share
2 answers

I made you an example. http://jsfiddle.net/kb3Kf/2/

The main thing that was missing was that you gave the text Absolute Position, but did not give the wrapper a Relative, for example:

 .img-overlay { position: relative; } 

It is very simple, you can take it in many ways. Please tell me what you wanted.

+7
source

You simply could not set the position of the parent img-overlay element. When something has an โ€œabsoluteโ€ position, it refers to where it refers to its parents. Parent must have positioning.

 .img-overlay { position: relative; width: 300px; } .img-overlay img { width:100%; } .overlay { position: absolute; width:100%; height: 100%; top:0px; left:0px; background-color: rgba(255,255,255,0.5); } 
+2
source

Source: https://habr.com/ru/post/951497/


All Articles