object-fit & object-position (CSS GRID) 图像上的居中文本叠加

Centered text overlay on image that is object-fit & object-position (CSS GRID)

我想知道是否可以在 object-fit: contain; 的图像上放置一个居中的文本叠加层(标题) AND object-position:左上角; (即不居中)

图像显示在 CSS 网格中。 (显示:网格;)

我正在尝试做的事情的例子:

.container {
  height: 40vw;
  width: 40vw;
  border: 1px solid black;
  display:grid;
}

img {
  max-width: 100%;
  max-height:100%;
  height: 100%;
  width: 100%;
  object-fit: contain;
  object-position: left top;
}
<div class="container">
  <img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/A825/production/_103954034_gettyimages-990971906.jpg">
</div>

提前致谢!

这是众多解决方案之一:

.container上使用position: relative;,然后在文本上使用position: absolute;(这里我使用了h3)来重新定位它,使用-10vh 来自 top.

HTML:

<div class="container">
  <img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/A825/production/_103954034_gettyimages-990971906.jpg">
  <h3>LOREM IMPSUM</h3>
</div>

CSS:

.container {
  height: 40vw;
  width: 40vw;
  border: 1px solid black;
  display:grid;
  position: relative;
}

img {
  max-width: 100%;
  max-height:100%;
  height: 100%;
  width: 100%;
  object-fit: contain;
  object-position: left top;
}

h3 {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -10vw);
  top: 20vw;
}   

object-fit 控制替换内容如何适合其容器。您无权访问布局和定位方面的替换内容。在网格中实现您想要的效果的一种方法是添加一个新容器,根据容器值在图像上设置一些 width/height 属性,然后将文本相对于该图像,避免使用 Object Fit。

.container {
  align-items: start;
  height: 40vw;
  width: 40vw;
  border: 1px solid black;
  display:grid;
}

img {
  display: block;
  height: auto;
  margin: 0 auto;
  max-height: 40vw;
  max-width: 40vw;
}

.textcontainer {
  position: relative;
}

.textcontainer-x-text {
  color: limegreen;
  font-family: sans-serif;
  font-weight: bold;
  left: 50%;
  position: absolute;
  text-align: center;
  text-transform: uppercase;
  top: 50%;
  transform: translate(-50%, -50%);
}
<p>Portrait</p>
<div class="container">
  <div class="textcontainer">
    <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
    <img src="http://placehold.it/150x400">
  </div>
</div>

<p>Landscape</p>
<div class="container">
  <div class="textcontainer">
    <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
    <img src="http://placehold.it/300x150">
  </div>
</div>

<p>Square</p>
<div class="container">
  <div class="textcontainer">
    <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
    <img src="http://placehold.it/300x300">
  </div>
</div>