首页 > 解决方案 > 将文本放在没有“位置:绝对;”的图像上 并将其包装以适合 CSS 网格中的隔间

问题描述

.grid-container {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(18vw, 1fr) );
  grid-auto-rows: minmax(35vh, 1fr);
  gap: 20px 20px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  opacity:0.85;
  background: green;
  color: #efefef;
  font-size:2em;
  border-radius:10px;
  transition: all 0.3s linear;
}

.box img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  opacity: 0.6;
  filter: brightness(0) invert(1);
}

.box p  {
  position: absolute;
  font-size: calc(0.9em + 0.9vw);
  font-weight: bold;
}
<div class="grid-container">
  <a href='link' class="box">
    <img src="src/img.png"/>
    <p>TEXT</p>
  </a>
  <a href='link2' class="box">
    <img src="src/img2.png"/>
    <p>ANOTHER TEXT</p>
  </a>
  ...
</div>

一切正常,图像在其“盒子”中水平和垂直居中,文本也居中(v&h)并在图像上方。一切都响应窗口大小,因此每列的框越宽,文本越大。

唯一的问题是文本不会分成几行,并且会在某些窗口大小的情况下溢出其框。有没有办法使<p>元素中的文本根据框的大小换行?

我有多种变体,例如使用自动换行(溢出换行),将<img>and<p>放在另一个内部<div>,并且......但似乎没有任何效果。

=========================

根据评论进行编辑。

元素将position: absolute;.box p内容移出流程。也许更好的选择是通过另一种方法获得文本优于图像的效果。关于如何做的任何想法?

编辑标题以更好地描述评论后的问题

标签: htmlcssflexboxcss-positioncss-grid

解决方案


position: absolute使用时position: relative;,在父容器上使用以使子元素使用父元素作为其位置参考(位置:相对和位置:绝对摘要此处)。另外,补充.box p { text-align: center }

.grid-container {
  display: grid;
  grid-template-columns: repeat( auto-fit, minmax(18vw, 1fr) );
  grid-auto-rows: minmax(35vh, 1fr);
  gap: 20px 20px;
}

.box {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity:0.85;
  background: green;
  color: #efefef;
  font-size:2em;
  border-radius:10px;
  transition: all 0.3s linear;
}

.box img {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  opacity: 0.6;
  filter: brightness(0) invert(1);
}

.box p  {
  position: absolute;
  font-size: calc(12px);
  font-weight: bold;
  text-align: center;
}
<div class="grid-container">
  <a href='link' class="box">
    <img src="src/img.png"/>
    <p>TEXT</p>
  </a>
  <a href='link2' class="box">
    <img src="src/img2.png"/>
    <p>ANOTHER TEXT that is much longer to show that you can center the text.</p>
  </a>
  ...
</div>


推荐阅读