无论图像宽度如何,如何将文本块放置在图像上

问题描述 投票:0回答:1

我不太熟悉 CSS,不知道如何保持文本块相对于图像宽度的覆盖。当我将图像宽度从 100% 更改为 50% 时,文本块保留在原来的位置,而不是保留在图像“内部”。

这是我正在使用的代码:

<!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>
html css image text overlay
1个回答
0
投票

嗯,这是因为您的

text-block
div 位于
absolute
container 
div,因此只有当该元素发生更改时,
text-block
div 才会响应。您可以通过更改
container
元素的 with 来简单地更改此设置,因为它是控制文本块位置的父元素 这是代码:

.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>

© www.soinside.com 2019 - 2024. All rights reserved.