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.


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>
source share