【问题标题】:How can I center an <img> inside a div and have it scale with the div's height?如何在 div 中居中 <img> 并使其随 div 的高度缩放?
【发布时间】:2015-08-15 07:29:26
【问题描述】:

我正在使用居中的 imgs 作为某些图块的背景。我试图让这些图像随其父 div 的高度缩放,如果它们更宽,则它们的父级让他们隐藏溢出。

例子:

* 我现在可以正常使用了。答案如下,我正在更新此代码以显示我需要用来让它工作的所有内容 *

HTML

<div class="container">
    <img class="derp" src="http://gridiculo.us/images/kitty02.jpg">
</div>

CSS:

.container {
    height:250px;
    width:50%;
}
.derp{
  object-fit: cover;
  height: 100%;
  width: 100%;
}

这是一个近似示例:http://codepen.io/chriscoyier/pen/myPMGB

不同之处在于我使用的是 s 而不是 background-image,而不是 img 完全填充 div,它会适合高度并隐藏宽度溢出。

我试图避免使用背景图像,因为我使用了很多这样的图块,并且为每个图块都制定 CSS 规则是行不通的。

【问题讨论】:

  • 如果是背景,为什么不使用 CSS 背景(带有背景比例、背景位置等)。
  • @marc 每个元素将使用不同的 URL,我尽量避免使用背景图像,因为它们有大量的 CSS 规则。

标签: css image overflow center hidden


【解决方案1】:

根据您需要支持的浏览器数量,我建议您使用 object-fit!支持它的是okay if you can ignore IE,但如果您的项目符合条件,我认为今天使用它没有问题。另外,总是有一个polyfill

您可以在on CSS-Tricks.com 找到关于该物业的精彩摘要。它基本上与 background-size 类似,但适用于 &lt;img&gt; 标签。在您的情况下,object-fit: cover; 可以解决问题。

我在 CodePen 上创建了a little demo,向您展示了它是如何工作的。

img {
  height: 100%;
  object-fit: fill;
  width: 100%;
}

【讨论】:

    【解决方案2】:

    为了使用 div 的高度来缩放它,我将高度从 px 更改为 % - 这样,div 越大,图片越大。为了确定图像,我会在图像 css 中使用边距。看起来像这样:

        .derp{
            height:80%;
            width:80%;
            margin:10%;
         }
    .container {
        height:250px;
        width:50%; /* needed */
        /* inner img is centered horizontally */
        vertical-align:top;
        text-align:center;
        overflow-x:hidden;
    }
    <div class="container" style="background-color:gray"> <!-- The background is there so you could see the image relative to the div -->
        <img class="derp" src="http://gridiculo.us/images/kitty02.jpg">
    </div>

    【讨论】:

    • 有没有办法在隐藏图像溢出宽度的情况下保持纵横比?
    • 是的 - 按照 pentz 的建议,将 object-fit: cover; 添加到 derp 类中。
    【解决方案3】:

    保持图像纵横比的最佳方法是将宽度设置为自动(这是默认行为,因此您无需显式设置)。使用简单的overflow:hidden,它几乎可以按照您的意愿工作。

    困难的部分是水平居中的。你可以试试这个答案:css to center a image horizontally

    但是,如果您的所有图片尺寸不同,则需要为每张图片制定一条规则。在这种情况下,将图像设置为background-img 对于语义和可访问性会更好(因为您的图像在页面中没有意义,它不传达任何信息,它是装饰)。 &lt;img&gt; 将被屏幕阅读器读取(alt 属性),在您的情况下,它不会帮助盲人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 2013-10-04
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多