【问题标题】:How to get multiple images to auto resize and stay centered within a div如何让多个图像自动调整大小并在 div 中保持居中
【发布时间】:2013-11-22 16:20:00
【问题描述】:

我试图让多个大学徽标图像连续缩小,因为浏览器宽度变小而不溢出其容器 div,就像我对上面的蓝色图片所做的那样。图片通过应用 100% 的最大宽度和高度在其 div 内缩放。但是徽标图像不会以相同的方式缩放并溢出 div。

这是一个活生生的例子:http://feroze.org/new-education/ - 尝试调整大小,看看我的意思

这是徽标容器 div 灰色条的 css

#partners
  height 105px
  background-color #eee
  white-space nowrap
  width 100%

这是应用于徽标图像本身的 css

.logo-image
  vertical-align middle
  padding 13px
  max-width 100%
  display inline

如您所见,我在灰色条中垂直对齐它们。但是随着条形图的缩短,我希望图像保留在 div 内并根据容器 div 调整大小。

任何帮助将不胜感激!谢谢

【问题讨论】:

  • 介意分享网站 URL 或创建 Fiddle?

标签: html css image responsive-design image-resizing


【解决方案1】:

不确定您已经获得了什么 HTML,但是如果图像都包含在 <div><li> 中,那么您可以使用 display: table;display: table-cell 来确保无论有多少图像,它们'将始终正确地适应宽度。

body {
  margin: 0;
}

#partners {
  height: 105px;
  background-color: #eee;
  white-space: nowrap;
  width: 100%;
  display: table;
}

.logo-image {
  vertical-align: middle;
  padding: 13px;
  display: table-cell;
}

.logo-image img {
  max-width: 100%;
}
<div id="partners">
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
  <div class="logo-image">
    <img src="http://placehold.it/120x80" alt="Placeholder Image" />
  </div>
</div>

Working demo here.

【讨论】:

  • 天啊!非常感谢,我一直在玩这个,但我无法得到它,但这完美无瑕!我很高兴非常感谢你。我多次搜索堆栈溢出,但找不到解决此问题的问题或答案。你是最好的,如果我能多次投票,我会感谢
  • 啊,虽然这在 Firefox 中不起作用。你知道 Firefox 的修复方法吗?
  • 我在 Firefox 中找到了它。只需将宽度 100% 添加到 .logo-image img 看到这个问题:stackoverflow.com/questions/14970591/…
【解决方案2】:

有三种方法可以做到这一点:

首先,您可以将最大宽度设置为 100%/图像数量(在本例中为 6 个)。 box-sizing 是一个新的 CSS 属性,包含宽度内的填充。

因此,您可以将填充设置为您想要的任何内容,但如果您将 box-sizing 设置为 border-box 和硬编码的宽度,则宽度将永远不会改变(当然,除非您有溢出)。

box-sizing: border-box;
max-width: 16%;

其次,您可以使用新的 CSS 函数 calc()。由于每边有 13px 的填充,我们减去 26px。

max-width: calc(100% / 6 - 26px);

最后,您可以使用 calc() 和 box-sizing,无需减去 26px。

box-sizing: border-box;
max-width: calc(100% / 6);

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2016-04-07
    • 2015-02-23
    • 2014-09-30
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多