我想知道是否可以在适合对象的图像上放置一个居中的文本叠加层(标题):包含; AND 对象位置:左上; (即不居中)
图像正在 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>
提前致谢!
最佳答案
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>
关于html - 居中文本叠加在适合对象和对象位置的图像上 (CSS GRID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935713/