css 文本与背景图像对齐

xxslljrj  于 2023-01-14  发布在  其他
关注(0)|答案(2)|浏览(151)

我有一个图像,我想把文字放在顶部,但在特定的区域,文字是动态的,所以不能保存为静态图像。和图像是不是全宽的,所以我不能只是把它固定为100%的宽度。
我不确定这是否可行,但我尝试了不同的方法,虽然我可以将文本放置在上面,但就间距而言,这是非常随机的。
我尝试了多种不同的方法,但是不能让它在不同的屏幕尺寸下工作一致。如果我把屏幕拖到一个更高的分辨率上,文本就会移动。
在我的CSS中,我尝试过不同的间距和位置,比如绝对或相对,但都无法正常工作。

.rank{
    position: absolute;
    bottom: 90px;
    left: 90px;
  }
  
.score {
    position: absolute;
    top: 90px;
    left: 90px;
  }
  .custom-container {
    position: relative;
    text-align: center;
    color: white;
  }
<div>
  <img src="https://placekitten.com/368/560" style="width:368;height:560px;" alt="scorecard">
  <div class="rank"><p class="text-white display-6">#1</p></div>
  <div class="score"><p class="text-white display-6">135</p></div>
</div>

但我也有同样的问题。有可能吗?

o75abkj4

o75abkj41#

你要做的就是把容器的display属性设置为relative,这样它就可以相对于容器体定位,并把文本设置为绝对文本,这样文本就可以在你想要的地方和图像保持一致。
您正在添加像素位置,请将其更改为相对值(%)。这里的主要问题是边距。您必须将其更改为相对值,如1%,否则它将采用常量值。同时将字体大小更改为相对值。我建议使用vw(垂直高度/宽度),它可以根据父字体大小调整字体大小。如果您有任何疑问,请向下评论。谢谢。

.container {
           
            margin: 3%;
            position: relative;
        
        }
        .container img
        {
       
        width:70%;
        height:60%;
        }
  
        .first-txt {
        font-size:4vw;
        margin-top:1%;
            position: absolute;
            top: 0%;
            left: 1%;
            color:white;
        }
  
        .second-txt {
         font-size:4vw;
        margin-bottom:1%;
            position: absolute;
            bottom: 2%;
            left: 1%;
            color:white;
        }
<!DOCTYPE html>
<html>
  
<head>
   
</head>
  
<body>
    <div class="container">
        <img src="https://img.freepik.com/free-photo/wide-angle-shot-single-tree-growing-clouded-sky-during-sunset-surrounded-by-grass_181624-22807.jpg" >
        <p class="first-txt">
           your text
        </p>
          
        <p class="second-txt">
           your text
        </p>
    </div>
</body>
  
</html>
qxsslcnc

qxsslcnc2#

你使用像素作为所有的尺寸单位。这对于所有的屏幕都是固定的。如果你尝试使用不同的单位,相对单位比如%会比绝对单位缩放得更好。
https://www.w3schools.com/cssref/css_units.php此链接可能也有助于解释

相关问题