如何在流体宽度容器中居中裁剪图像(<img>)

Bry*_*yce 50 css image fluid-layout responsive-design fluid-images

当流体宽度(基于百分比)容器太小而无法显示整个图像时,如何使图像保持居中?

在此输入图像描述

如何将图像置于其容器中心

这意味着当容器太小时,它应该显示图像的中间而不是侧面.

Bry*_*yce 99

什么时候工作

您可能有一个容器,其中包含一些内容,例如两个内容,<div>每个内容各50%,彼此相邻.在这个例子中,我们只能说明容器的一个子节点: 在此输入图像描述

我们将外部矩形.container,内部矩形.content和图像命名img.这种安排完全没问题,只要.content总是宽的img.

什么时候打破

由于我们处理百分比并且可能使用响应式设计,因此情况可能并非总是如此.如果.content比较薄img,将会出现裁剪:

在此输入图像描述

问题

如果最有趣的部分img位于中心,我们需要让浏览器均匀地裁剪两个边缘 - 无论宽度.content是多少,都可以看到它的最佳部分.

在此输入图像描述

解决方案

幸运的是,解决方案是可行的.更好的是,不需要额外的标记.

.content {
    width: 90%; /* or whatever is required */
    text-align: center; /* ensures the image is always in the h-middle */
    overflow: hidden; /* hide the cropped portion */
}

img {
    position: relative; /* allows repositioning */
    left: 100%; /* move the whole width of the image to the right */
    margin-left: -200%; /* magic! */
}
Run Code Online (Sandbox Code Playgroud)

  • 我想知道的是它是如何工作的。 (2认同)
  • 这很奇怪,它只能在一定的尺寸以上工作.[请参阅此小提琴](http://jsfiddle.net/ha65p/17/)并上下调整窗格大小. (2认同)

Gab*_*iel 19

对于新浏览器,您可以翻译它

figure{
    width: 100%;
    text-align: center;
    overflow: hidden;
}
img{
    position: relative;
    left: 50%;
    transform: translate(-50%,0)
}
Run Code Online (Sandbox Code Playgroud)

要支持IE8,您仍然可以使用@BryceHanscomb上面介绍的技术.

.no-csstransforms figure img {
    left: 100%; /* move the whole width of the image to the right */
    margin-left: -200%; /* magic! */
}
Run Code Online (Sandbox Code Playgroud)