图像上的居中文本如何使用HTML和CSS在网格上重叠?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (62)

https:/codepen.io/lifutar/PEN/JZaVNX

HTML:

<div id = "element">
  <div class = "item" id ="box_one"><img src = "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/wp-content/uploads/2017/04/2018-BMW-M4-CS-PLACEMENT-626x383.jpg?crop=1xw:1xh;center,center&resize=450:*" id="bmw" class = "car overlay">
    <p class = "text">Wannabe Baller</p>
  </div>
  <div class = "item" id="box_two"><img src ="https://assets.mbusa.com/vcm/MB/DigitalAssets/Vehicles/ClassLanding/2018/S/Maybach/BASE/GALLERY/2018-MAYBACH-GALLERY-001-SET-A-WP.jpg" id="maybach" class = "car overlay"><p class="text">Savvy Entrepreneur</p></div>
  <div class = "item" id ="box_three"><img src="https://icdn-3.motor1.com/images/mgl/nvEe6/s1/2019-audi-a7-sportback-photo-shoot-in-olso.jpg" class = "car overlay" id="audi">
  <p class= "text">I'm not like the other guys</p></div>
  <div class = "item" id ="box_four"><img src = "https://files2.porsche.com/filestore/image/multimedia/none/911-carrange-jdp-2017/normal/2269da21-2995-11e7-9f74-0019999cd470/porsche-normal.jpg" class = "car overlay"id = "porsche"><p class= "text">I know a lot about cars</p></div>
  <div class = "item" id = "box_five"><img src ="https://jaguar.ssl.cdn.sdlmedia.com/636553494257956285DM.jpg?v=22" id = "jaguar" class = "car overlay"><p class = "text"> My car is the fastest in the land</p>5</div>
  <div class = "item" id = "box_six"><img src = "https://article.images.consumerreports.org/h_436,w_598/prod/content/dam/CRO%20Images%202017/Cars/October/CR-Cars-598-2018-Lexus-LS500-10-17" id = "lexus" class = "car overlay">
    <p class = "text">I'm better than them Toyota driving folks</p>
  </div>
</div>
THE CSS:

    #element{
  display: inline-grid;
  grid-template-columns: [one] 200px [two] 200px [three] 200px;
  grid-template-rows:200px 200px 200px;
  position:relative;
  left:200px;
  top:100px;

}
.item
{
  border: 1px solid red;
}
#bmw
{
  max-width:100%;
}
.item:hover
{
  transform:scale(1.5);
}
.overlay
{
  height:100%;
  width:100%;
}
.text
{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color:yellow;
    max-width:100%;

}

代码在^上。我遇到的问题是,所有的文本都在网格的第5框中相互交织在一起,怎么办?

提问于
用户回答回答于

发生此重叠是因为你正在使用position absolute;

因为<p>元素<div>与班item,没有位置,文本相对于它们的下一个最接近的祖先,<div>与班element

要达到你想要的效果,试着给你itemposition: relative;

扫码关注云+社区

领取腾讯云代金券