我有一个水平和垂直居中的 div 容器,其中的图像也水平和垂直居中,以尽可能多地使用容器空间。图像可以是横向和纵向。 为了使图像在容器内居中,我使用
position: absolute
设置图像样式。
我想按照相对于图像底部的方式向图像添加标题。
我的代码笔:https://codepen.io/mopk/pen/OJYJLLq
我看过类似的问题 相对于图像的绝对位置 但它的不同之处在于它不会绝对定位图像,也不会使其水平和垂直居中。
也许问题出在我使用的图像居中。
我尝试了各种图像居中,发现基于
position: absolute
的居中导致标题很难与图像联系起来。而基于 transform: translateX(-50%) translateY(-50%);
的内容会导致不同视口的标题位置不可预测。您在寻找这样的东西吗?
* {
box-sizing: border-box;
}
#container {
display: grid;
place-content: center;
border: 1px solid black;
}
figure {
border: 2px solid red;
height: fit-content;
}
figcaption {
text-align: center;
border: 2px solid red;
}
<div id="container">
<figure>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Portrait_of_Yi_Haeung_%28National_Museum_of_Korea%29.jpg/403px-Portrait_of_Yi_Haeung_%28National_Museum_of_Korea%29.jpg">
<figcaption>My caption</figcaption>
</figure>
</div>