html - 在可缩放图像上定位文本

标签 html css flexbox

#hero-container {
    display: flex;
    position: relative;
    height: 520px;
}

.hero {
    position: absolute;
    left: 0;
    top: 0;
}
  
#text {
    z-index: 100;
    position: absolute;
    color: white;
    font-size: 3vw;
    font-weight: bold;
    left: 150px;
    top: 40px;
}
    
#text2 {
    z-index: 100;
    position: absolute;
    color: white;
    font-size: 2vw;
    font-weight: bold;
    left: 150px;
    top: 70px;
}
    
#hero-container img {
    display: flex;
    width: 100%;
}
<html>
  <head>
  </head>
  <body>
    <div id="hero-container">
      <img class="hero" src="https://vreauperle.ro/images/banners/hero-image.jpg"></img>
      <p id="text">
        First text here
      </p>
      <p id="text2">
        Secondary
      </p>
    </div>
  </body>
</html>

我在固定容器中有一张 width:100% 的图片。因为我的图像调整了大小,文本没有跟随并保持在相同的位置,因此移动到容器上。

如何在不添加 1000 个媒体查询的情况下使文本保持在图像的中心(垂直)和左侧,并填充几个像素(水平)?

最佳答案

您可以大大简化您的 CSS:

  1. 移除 flex(除非有某些特定原因您需要它)。
  2. 将您想要垂直居中的文本包裹在 divtranslateY(-50%) 中。
  3. 确保图像周围的包装器具有 position:relative

#hero-container {
  position: relative;
}

#center-text {
  z-index: 100;
  position: absolute;
  color: white;
  font-weight: bold;
  left: 15%;
  top: 50%;
  transform: translateY(-50%);
}
  
#text {
  font-size: 3vw;
  margin: 0;
}
    
#text2 {
  font-size: 2vw;
  margin: 0;
}
    
#hero-container img {
  width: 100%;
  height: auto;
}
<div id="hero-container">
  <img class="hero" src="https://vreauperle.ro/images/banners/hero-image.jpg" />
  <div id="center-text">
    <p id="text">
      First text here
    </p>
    <p id="text2">
      Secondary
    </p>
  </div>
</div>

无论您的分辨率如何,这都将完全响应,并且应该在 IE10+(或带有 -ms-transform 前缀的 IE9+)中工作,如果您使用一些更标准的字体大小(而不是 vw).

关于html - 在可缩放图像上定位文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001412/

相关文章:

javascript - # url 部分隐藏和显示

html - CSS 未对齐元素无法将其放置到位

html - 使用在父 div 上设置的 border-radius 修剪图像 Angular 在 Safari 中不起作用

html - 带有列式标题的 Flexbox 图像

html - 文本溢出省略号在嵌套的 flexbox 中不起作用

javascript - 单击箭头更改图像

javascript - HTML CSS 试图创建一个显示在文本上的输入字段

java - 需要逻辑解决不可数循环困境

css - 在 CSS 中设置字体大小时,字母的实际高度是多少?

html - 不是正确的 css 方法?