I have the following case:
- Image which its width is less than the page width.
- Image needs to be centered within its parent
div
(Which is wider). - Overlay text should be displayed on the image on one of its corners.
- Image can not be stretched. Image will appear in its native size.
- The image size can not be set in
CSS
as this template will be used for many images in different size.
So the code I came up with is given in https://jsfiddle.net/RoyiA/gdezys7j Or (Must be viewed in Full Screen so the image will be centered):
@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}
.image-container {
position: relative;
font-family: Arial;
}
.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}
.image-text-block {
position: absolute;
display: block;
top: 100px;
left: 10px;
background-color: rgba(100, 100, 100, 0.5);
color: white;
padding-left: 10px;
padding-right: 10px;
}
<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>
<div class="image-container">
<img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
<div class="image-text-block">
<h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
<p>Image: <a href="https://www.flickr.com/photos/151740882@N05/47029584231">Jane</a> by Mireille Lannoo</p>
</div>
</div>
The problem I'm having is that the text div
is relative to the position of its parent div
while the image is centered. How can address that?
Your image container does not have a set width, and therefore will be the width of the screen unless you set a width. You are positioning the text to the top left corner of the container, not the image.
I would suggest wrapping the image-container block inside another div which purpose is to center it. That way the image-container block has the width of the image and your absolute positioning of the caption box should work as intended.
Just a couple of changes like so.