【问题标题】:Center div inside image with flexbox [duplicate]使用 flexbox 在图像中居中 div [重复]
【发布时间】:2020-11-08 00:29:59
【问题描述】:

尝试使用 flexbox 在图像中居中 div(我只想要 flexbox),但由于 img 没有结束标签,我无法使其工作。怎么办?

.uno {
   display: flex;
   justify-content: center;
   align-items: center;
}
<div class="uno">
   <img src="https://www.placecage.com/300/300" alt="">
   <h1>Center this text</h1>
</div>

这会将我的文本放在中间,但在 img 的右侧。只有 flexbox 解决方案。

【问题讨论】:

  • 您是否要在图片上方放置文字?
  • 如果您将图像作为背景。将文本对齐到中心会很容易
  • @KPranavRam - 不,水平和垂直居中
  • @DanielprabhakaranN - 我知道,但我不能。就像这里介绍的那样。
  • img 中的 Div,hm 很有趣...

标签: html css flexbox


【解决方案1】:

要将文本放置在图像上,请为 h1 元素提供绝对位置,并在容器元素上添加相对位置。

由于您已将 flex 容器上的 justify-contentalign-items 属性设置为 center,因此当文本放置在图像上时,它将水平和垂直居中。

.uno {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  position: absolute;
}
<div class="uno">
  <img src="https://www.placecage.com/300/300" alt="" />
  <h1>
    Center this text
  </h1>
</div>

【讨论】:

    【解决方案2】:

    您不能将其他元素放在img 标记内。正如其他人所说,使用background-image 会更有意义,但我猜你需要这样是有原因的。

    根据您的需要,您必须将图像设置为position: absolute; z-index: 0;,将h1 设置为z-index: 1;,此外,需要重置.uno 的高度,否则可能会剪掉边缘页面。

    body {
      height: 100vh;
      width: 100%;
    }
    
    .uno {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }
    
    img {
      position: absolute;
      z-index: 0;
    }
    
    h1 {
      z-index: 1;
    }
    <div class="uno">
      <img src="https://www.placecage.com/300/300" alt="" />
      <h1>
        Center this text
      </h1>
    </div>

    喜欢这张图片。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-15
      • 2017-01-29
      • 2016-05-17
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2021-07-16
      相关资源
      最近更新 更多