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

如何在容器中的图像上覆盖文本--并将文本保留在容器中

  •  2
  • abalter  · 技术社区  · 7 年前

    我遵循在无数个地方给出的解决方案,如何在图像上覆盖文本,使用 relative absolute position: absolute 从容器中跳出并达到极限 top right

    我很乐意使用背景图像,但我需要技巧使容器与图像大小匹配,我不知道如何使其流动。

    这似乎是一个非常简单的问题,人们总是在寻找解决方案。另外,在不透明图像上叠加文本,需要使用 :after

    .container {
      margin: 0 10%;
    }
    .container img {
      position: relative;
      width: 100%;
    }
    
    #div1 .text {
      position: absolute;
      bottom: 0;
      right: 0;
    }
    
    #div2 .text {
      position: absolute;
      top: 0;
      left: 0;
    }
    <div id="div1" class="container">
      <img src="http://placehold.it/800x200" />
      <div class="text">
        <h3>Top Image</h3>
        <p>This text should be in the bottom right of the top image.</p>
      </div>
    </div>
    
    <div><p>A bunch of miscellaneous text here.</p></div>
    
    <div id="div2" class="container">
      <img src="http://placehold.it/800x200" />
      <div class="text">
        <h3>Lower Image</h3>
        <p>This should be in the top left of the lower image.</p>
      </div>
    </div>
    2 回复  |  直到 7 年前
        1
  •  2
  •   Julio Feferman Mohamed Mostafa Goda    7 年前

    你需要设置 position:relative .container 哪个是正确的容器 .text img .文本 而不是它的容器。

    .container {
      margin: 0 10%;
      position: relative;
    }
    .container img {
      width: 100%;
    }
    
    #div1 .text {
      position: absolute;
      bottom: 0;
      right: 0;
    }
    
    #div2 .text {
      position: absolute;
      top: 0;
      left: 0;
    }
    <div id="div1" class="container">
      <img src="http://placehold.it/800x200" />
      <div class="text">
        <h3>Top Image</h3>
        <p>This text should be in the bottom right of the top image.</p>
      </div>
    </div>
    
    <div><p>A bunch of miscellaneous text here.</p></div>
    
    <div id="div2" class="container">
      <img src="http://placehold.it/800x200" />
      <div class="text">
        <h3>Lower Image</h3>
        <p>This should be in the top left of the lower image.</p>
      </div>
    </div>
        2
  •  0
  •   vtvcode    7 年前

    我不太确定是否有足够的信息。我假设您的容器宽800px,高200 px(我使用了最小高度,以防您的容器增加其高度)。如果您可以提供更具体的信息,那将是非常好的(有更复杂的方法使用对象位置属性(etc))使其更“智能”。

    img {
      max-width: 100%;
      display: block;
      height: auto;
    }
    
    .container {
      position: relative;
      min-height: 200px;
      width: 800px;
      margin: 0 10%;
    }
    
    .container img {
      z-index: 500;
      top: 0;
      left: 0;
    }
    
    .container .text {
      position: absolute;
      z-index: 1000;
    }
    
    #div1 .text {
      bottom: 0;
      right: 0;
    }
    
    #div2 .text {
      position: absolute;
      top: 0;
      left: 0;
    }