html - 如何将未知尺寸的图像置于固定尺寸的 float 框中居中?

标签 html css css-float css-position

在每一行中,我有三个固定尺寸的盒子(蓝色)(宽度:299px,高度:307px) 每个盒子里都有一个尺寸未知的图像(粉红色)。我只知道 max-width: 262pxmax-height: 200px。图像下方有一些简短的两三行文本。我需要将图像在文本上方的空间中水平和垂直居中。

我将框设置为float:left,并将图像设置为position:absolute。我现在不知道如何让它工作:(

Images need to be centered

最佳答案

最简单的方法是使用表格显示,但这需要标记中包含大量容器元素。如果文本高度也固定,我会使用描述的“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>

测试:http://cssdesk.com/MmrVV

关于html - 如何将未知尺寸的图像置于固定尺寸的 float 框中居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20792367/

相关文章:

javascript - 循环内 jquery .hover 函数的动态弹出窗口

javascript - 在具有行标题和列标题的表格中,给定列标题文本和单元格文本,如何选择单元格 (td)?

html - Node-WebKit 和 html5 视频

html - 使 float 的 div 容器保持原位,因为它们上方的 div 展开并重叠

javascript - "ellipse"通过JS创建的元素没有出现在html中

css - 防止在 JQuery Mobile 中的文本字段前后换行

css - angular SSR 引导应用程序时如何防止 css 动画再次出现

jquery - 视差滚动更平滑

css - CSS 规则 "clear: both"有什么作用?

css - 图像和分隔符定位