代码之家  ›  专栏  ›  技术社区  ›  ampro415

如何在不考虑图像宽度的情况下将文本块放置在图像上

  •  0
  • ampro415  · 技术社区  · 2 年前

    我不太熟悉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>
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Izebeafe    2 年前

    嗯,这是因为你 text-block div已定位 absolute container div,因此只有当该元素发生变化时 文本块 div将作出响应。您可以简单地通过更改的 container 元素,因为它是控制文本块位置的父级 这是代码:

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