如何使用flexbox将文字正确放置在图像上

时间:2020-05-09 00:08:14

标签: html css flexbox css-position absolute

我正试图在包含图像和文本的div的左上角放置一些文本。我可以使用CSS绝对定位使其正常工作,但是文本没有响应,并且会根据屏幕大小移动。我需要文本能够响应并根据屏幕大小进行调整,以使其相对于图像保持在相同位置。

我也在使用引导程序,我认为它没有作用,但是可能是我不知道的隐蔽之处。

这是我当前正在使用的代码:

HTML

<div class="container-fluid"> 
  <div class="col-md-12 d-flex jumbo">
    <img class='img-fluid jumbo-image' 
         src= 'https://i.postimg.cc/8cXs8gZ9/working-horse.jpg' />
    <h2 class='jumbo-text'>Jungers Farm</h2>
</div>

CSS

.jumbo {
  position: relative;
}

.jumbo-image {
  margin-top: 85px;
  box-shadow: 15px 15px grey;
}

.jumbo-text {
  display: inline-block;
  font-size: 3em;
  color: #3386ff;
  text-shadow: 2px 2px 5px red;
  position: absolute;               /* remove from document flow */
  left: 5%;                         /* Left */
  top: 18%;                         /* Top */
}

如下面的代码笔所示,文本没有响应,并且随着屏幕的变化在图像上移动。因此,我的定位之所以不是直线左移,是0%,顶部是0%。但是,当屏幕大于768px时,通常看起来或多或少就像我想要的。

Codepen

以下是我尝试使用flexbox的尝试,但文本显示在屏幕右侧之外:

Codepen

使用flexbox甚至可以做到吗?如果不是,是否可以使用CSS CSS Absolute定位方法使文本具有响应性?

1 个答案:

答案 0 :(得分:0)

因此,如果我正确理解了您的问题,那么问题是,当更新视口大小时,图像将按照比例缩放,从而导致文本不再位于图像的所需部分。一种可能的解决方法是删除img标签,然后将其设置为父div的背景图像。然后,您可以绝对定位h2标签,无论视口大小如何,文本始终将保留在背景图像上。当然,使用此方法,您将必须显式设置父div的宽度和高度,或使用padding-bottom技巧来设置高度。

<div class="container-fluid"> 
<div class="col-md-12 d-flex jumbo" 
style="background:url(https://i.postimg.cc/8cXs8gZ9/working-horse.jpg); 
background-position:center center; background-size:cover; background- 
repeat:no-repeat; width:100%; padding-bottom:65%;">
  <h2 class='d-flex jumbo-text'>Jungers Farm</h2>
</div>
相关问题