I am not well-versed with CSS and can’t figure out how to keep a text block overlay relative to the width of my image. When I change the image width from 100% to 50%, the text block stays where it’s at instead of staying "inside" the image.
This is the code I’m using:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
position: relative;
font-family: Arial;
}
.text-block {
position: absolute;
bottom: 20px;
right: 20px;
background-color: black;
color: white;
padding-left: 20px;
padding-right: 20px;
}
</style>
</head>
<body>
<div class="container">
<img src="https://xofarragio.com/resources/graphics/placeholder_1920x1280_01.png" alt="Nature" style="width:100%;">
<div class="text-block">
<h4>Testing</h4>
<p>This is a test</p>
</div>
</div>
</body>
</html>
>Solution :
Well, it’s because your text-block div is positioned absolute to the container div, and so it is only when that element changes that the text-block div will respond. You can simply change this by changing the with of the container element, as that is the parent that controls the position of the text-block
This is the code:
.container {
position: relative;
font-family: Arial;
width: 50%; /* only line added. Change wight here instead of in img*/
}
.text-block {
position: absolute;
bottom: 20px;
right: 20px;
background-color: black;
color: white;
padding-left: 20px;
padding-right: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<img src="https://xofarragio.com/resources/graphics/placeholder_1920x1280_01.png" alt="Nature" style="width:100%;">
<div class="text-block">
<h4>Testing</h4>
<p>This is a test</p>
</div>
</div>
</body>
</html>