html - 将文本放在没有“位置:绝对;”的图像上 并将其包装以适合 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
内容移出流程。也许更好的选择是通过另一种方法获得文本优于图像的效果。关于如何做的任何想法?
编辑标题以更好地描述评论后的问题
解决方案
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>
推荐阅读
- nginx - 有什么方法可以让您的 nginx 代理不转发 HTTP -> HTTPS 仅针对特定 URL?
- f# - 不理解 F# 中的泛型
- php - 即使缺少扩展,如何强制作曲家安装?
- javascript - Javascript 使用 ts-node 设置无效的数组长度
- python - 抓取最后一个“下一页”后的 BeautifulSoup AttributeError
- go - 在反射中设置结构的值时遇到问题
- sql - 关于平均值的SQL语句
- sonos - 处理事件帖子的最佳实践
- python-3.x - 如何使用发布日期列迭代数据框以制作每日映射表
- apache - Apache - 将 png 作为文本 / html 服务