无法在 css 网格系统中将文本定位在图像上

Cannot position text over image in a css grid system

我想做的是在这些图像上放置文本。我希望它们位于左下角,但无论我尝试什么,似乎都无法让它们工作。我可以更改它们的大小、颜色和填充,但无法将它们放在 div 中我想要的位置。任何建议都有帮助,我很感激!谢谢

HTML:

    <div class="grid">
    <div class="f f1">
        <h3>My Beautiful Dark Fantasy</h3>
    </div>
    <div class="f f2">
            <h3>My Beautiful Dark Fantasy</h3>
    </div>
    <div class="f f3">
        <h3>My Beautiful Dark Fantasy</h3>
    </div>
    <div class="f f4">
        <h3>My Beautiful Dark Fantasy</h3>
    </div>
    <div class="f f5">
        <h3>My Beautiful Dark Fantasy</h3>
    </div>
</div>

CSS

html {
height: 100%;
box-sizing: border-box;
}

body {
position: relative;
margin: 0;
padding-bottom: 6rem;
min-height: 100%;
font-family: "Helvetica Neue", Arial, sans-serif;
}


.nav {
background: #ddd;
padding: 20px;
margin: 0;
}

.nav a {
padding: 10px;
}

.grid { 
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 350px;
margin: 30px 150px 30px 150px;
position: relative;
}

.f {
width: 100%;
height: 100%;
position: relative;
background-repeat: no-repeat;
background-size: cover;
background-color: grey;
}

.f h3{
color: white;
margin: 0;
padding: 10px;
}

.f1 {
grid-column: 1/3;
grid-row: 1/3;
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 
url("/images/album/tyler.jpg");
}

.f2 {
grid-column: 3/4;
grid-row: 1/2;
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 
url("/images/album/dope.jpg");

}

.f3 {
grid-column: 3/4;
grid-row: 2/4;
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 
url("/images/album/kanye.jpg");

}

.f4 {
grid-column: 1/2;
grid-row: 3/4;
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 
url("/images/album/selfie.jpg");

}

.f5 {
grid-column: 2/3;
grid-row: 3/4;
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), 
url("/images/album/fantasy.jpg");

}


.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
background-color: #efefef;
text-align: center;
}

What I am trying to do is position text over these images.

在给定的例子中,尝试改变这个:

.f h3{
color: white;
margin: 0;
padding: 10px;
}

对此:

.f h3{
color: white;
margin: 0;
padding: 10px;
position:absolute;
left:0;
bottom:0;
}

在相对定位的 .f 中添加绝对定位应该可行。

一个好的解决方案是通过将 grid-columngrid-rows 设置为相同来将文本网格和图像网格相互堆叠。然后只需使用 z-index 将您的文本向前移动。

您现在可以轻松地将文本移动到任何地方。它也有反应。我们能够利用 cause of css grid 的非常强大的方法。您可以通过这种方法获得真正的创意。 Multi-stacking 一直致力于制作一个单页网页,您只需打开所需的页面即可到达页面的各个部分。希望这有帮助。

具有以下html

  <div class="item image-text-center">
    <img src="img/2.jpg" alt="">
    <div class="text">Hello, World</div>
  </div>

这将使文本居中

.item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.item.image-text-center .text{
  color: var(--white);
  padding: 10px;
  position:absolute;
  display: grid;
  align-self: center;
  justify-self: center;
}