首页 > 解决方案 > 我该如何解决这个相对/绝对问题?

问题描述

我正在尝试将此文本放在图像上,但它不起作用!我已经验证了代码中的所有内容,从将 css 链接到代码中的错误,但没有找到任何东西。

.pai {
  position:relative;
}

.filho {
  position:absolute;
  text-align:center;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="Estudos.css">
  </head>
  <body>
    <div class="pai">
      <img src="bgestudio.jpg" alt="">
      <div class="filho">
        <h1>Qualquer</h1>
      </div>
    </div>
  </body>
</html>

强文本 [1]:https ://i.stack.imgur.com/OsBdx.jpg

标签: htmlcss

解决方案


您需要使容器 div 与图像的宽度相同,然后文本 div 填充容器:

.pai {
  position:relative;
  display:inline-block; /* make this div as wide as the image - can be removed if the image is 100% width */
}

.filho {
  position:absolute;
  text-align:center;
  left: 0; 
  right:0;  /* left and right mean width will be 100%; */
  top:50%;
  transform: translateY(-50%); /* top 50 and translate mean it is vertically centered */
  
  color:white;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="Estudos.css">
  </head>
  <body>
    <div class="pai">
      <img src="https://www.fillmurray.com/200/300" alt="">
      <div class="filho">
        <h1>Qualquer</h1>
      </div>
    </div>
  </body>
</html>


推荐阅读