在每一行中,我有三个固定尺寸的盒子(蓝色)(宽度:299px,高度:307px)
每个盒子里都有一个尺寸未知的图像(粉红色)。我只知道 max-width: 262px
和 max-height: 200px
。图像下方有一些简短的两三行文本。我需要将图像在文本上方的空间中水平和垂直居中。
我将框设置为float:left
,并将图像设置为position:absolute
。我现在不知道如何让它工作:(
最佳答案
最简单的方法是使用表格显示,但这需要标记中包含大量容器元素。如果文本高度也固定,我会使用描述的“100%高度幽灵”技术here .
应用于您的案例:
.box{
text-align: center;
position: relative;
/* removes spaces between inline-block elements */
/* another way is to add some negative margin on them */
font-size: 0;
/* account for text height */
padding-bottom: 70px;
/* +box width, height, float props etc. */
}
.box p{
position: absolute;
bottom: 10px;
left: 5%;
width: 90%;
font-size: 14px;
}
/* the ghost, which forces vertical-align */
.box::before {
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
.box img {
display: inline-block;
vertical-align: middle;
/* here you have to resize your images to fit within the box */
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
标记:
<div class="box">
<img ... />
<p> text... </p>
</div>
关于html - 如何将未知尺寸的图像置于固定尺寸的 float 框中居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20792367/