如何将 img 在容器中垂直和水平居中 - img 可能比容器大
我有一个包含图像的容器,并且该图像是从应用程序加载的,因此容器的尺寸是已知的,而图像会有所不同。
我目前有以下 css:
#secondary_photos {
height: 100px;
width: 300px;
overflow: hidden;
}
#secondary_photos .small_photo {
float:left;
height: 100px;
width: 300px;
}
#secondary_photos .small_photo img{
height: 100%;
width: auto;
position: absolute;
bottom: 0px
}
#secondary_photos .small_photo img{
height: auto;
width: 100%;
position: absolute;
bottom: 0px
}
这对我来说“没问题”:它加载图像,调整其大小以占据容器宽度的 100% 并定位它,以便图像的下半部分显示在容器内 - 所以如果将宽度调整为 300 像素后图像最终高度为 200 像素,则仅显示图像底部 100 像素(任意设置)。
我想做的是始终显示图像的中间 - 因此在上面的示例中,图像将显示 50-150 像素(从顶部开始)。
I have a container that will contain an image, and this image is loaded from an application and so the dimensions of the container is known while the image will vary.
I currently have the following css:
#secondary_photos {
height: 100px;
width: 300px;
overflow: hidden;
}
#secondary_photos .small_photo {
float:left;
height: 100px;
width: 300px;
}
#secondary_photos .small_photo img{
height: 100%;
width: auto;
position: absolute;
bottom: 0px
}
#secondary_photos .small_photo img{
height: auto;
width: 100%;
position: absolute;
bottom: 0px
}
This works 'okay' form me: it loads the image, resizes it to take up 100% of the container's width and positions it so that the bottom-half of the image is displayed within the container - so if the image ends up being 200px high after resizing the width to 300px, only the bottom 100px of the image is displayed (an arbitrary setting).
What I'm trying to do is to always display the middle of the image - so in the example above, the image would display pixels 50-150 (from the top)..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于听起来您不知道页面加载时的图像大小,因此您可以使用 死中心和javascript来做你想做的事。流程如下:
(图像宽度/ 2 * -1)
。(图像高度/ 2 * -1)
。由于您可能还有比容器大的图像,因此您可以为此添加条件检查:
Since it sounds like you don't know the image size on page load, you could use a combination of dead centre and javascript to do what you want. The flow would be as follows:
(image width / 2 * -1)
.(image height / 2 * -1)
.Since you may also have images that are larger than your container, you could add a conditional check for this: