Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to position a text block over image regardless of image width

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading