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

没有白色背景的分层文本

  •  0
  • bigorangeduck  · 技术社区  · 4 年前

    我正试图完成Odin项目的“注册表格”,但我在将文本分层到图像上时遇到了问题。

    enter image description here

    如果我使用 position:absolute; 文本不考虑容器的宽度。

    如果我使用 position:relative; 我在文本下面有一个白色背景。

    我急需指导。

    非常感谢。

    <div class="container-one">    
        <h1>Sign up now!</h1>
        <img src="1.jpg" alt="">    
    </div>
    
    <style>
        img { 
            width: 100%;
            z-index: -1;
        }
    
        h1 {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            position: relative;
    
        }
    </style>
    
    3 回复  |  直到 4 年前
        1
  •  2
  •   Nick Vu    4 年前

    你就快到了 position: absolute .最后一件事是你需要设置 position: relative 到 .container-one 它是图像和文本的容器。

    <div class="container-one">
      <h1>Sign up now!</h1>
      <img src="https://images.unsplash.com/photo-1612151855475-877969f4a6cc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGQlMjBpbWFnZXxlbnwwfHwwfHw%3D&w=1000&q=80" alt="">
    </div>
    
    <style>
      .container-one {
        position: relative;
        width: 50%;
      }
      
      img {
        width: 100%;
        z-index: -1;
      }
      
      h1 {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        position: absolute;
      }
    </style>

    你可以查一下 this doc

    另一个解决方案是 background-image

    <div class="container-one">
      <h1>Sign up now!</h1>
    </div>
    
    <style>
      .container-one {
        position: relative;
        width: 50%;
        height: 100vh;
        background-size: contain;
        background-repeat: no-repeat;
        background-image: url('https://images.unsplash.com/photo-1612151855475-877969f4a6cc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGQlMjBpbWFnZXxlbnwwfHwwfHw%3D&w=1000&q=80');
      }
      
      h1 {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        position: absolute;
      }
    </style>
        2
  •  1
  •   Akhilesh B Chandran    4 年前

    试着这样做:

    .container-one{
      position: relative;  
    }
    
    img { 
      width: 100%;  
    }
    
    h1 {
      top: 30%;
      left: 0;
      width: 100%;
      position: absolute;
      z-index: 55;
      text-align: center;
    }
    

    基本上是你做的 h1 绝对定位。设定了更高的目标 z-index 这样它就会出现在图像元素的上方。此外,设置 container-one 相对定位,使你的 h1 将使用它来计算它的位置。

    您可以使用 top 。要将文本居中对齐,请使用 text-align 所有物

    这是答案 fiddle

        3
  •  0
  •   Steve Walson    4 年前

    最佳做法是将图像用作包含文本的div的背景图像。 你会轻而易举地掌控一切。