如何在流体宽度容器中居中裁剪图像 (<img>) [英] How to center crop an image (<img>) in fluid width container
问题描述
当图像的流体宽度(基于百分比)容器太小而无法显示整个图像时,如何使图像保持居中?
如何使图像在其容器内居中
这意味着当容器太小时,它应该显示图像的中间而不是侧面.
何时有效
您可能有一个容器,其中包含一些内容,例如两个
我们将命名外部矩形 .container
、内部矩形 .content
和图像 img
.这种安排非常好,只要.content
总是比img
宽.
什么时候坏了
由于我们正在处理百分比并且可能使用响应式设计,因此情况可能并非总是如此.如果 .content
比 img
更薄,就会发生裁剪:
问题
如果 img
最有趣的部分在中心,我们需要让浏览器均匀地裁剪两个边缘 - 无论 的宽度是多少,最好的部分都是可见的.content
是.
解决方案
幸运的是,解决方案是可能的.更好的是,不需要额外的标记.
.content {宽度:90%;/* 或任何需要的 */文本对齐:居中;/* 确保图像总是在 h-middle */溢出:隐藏;/* 隐藏裁剪部分 */}图片{位置:相对;/* 允许重新定位 */左:100%;/* 将图像的整个宽度向右移动 */左边距:-200%;/* 魔法!*/}
How do I get an image to stay centered when its fluid width (percentage based) container is too small to show the whole image?
How can I center the image inside it's container
This means it should show the middle of the image instead of the sides when container is too small.
When It Works
You might have a container that holds some content such as two <div>
s that are 50% wide each, sitting next to each other. For this example, we can illustrate just one child of the container:
We'll name outer rectangle .container
, the inner rectangle .content
and the image img
. This arrangement is perfectly fine, as long as .content
is always wider than img
.
When It Breaks
Since we're dealing with percentages and probably working with a responsive design, this may not always be the case. If .content
is ever thinner than img
, cropping will occur:
The Problem
If the most interesting part of img
is in the center, we need to get the browser to crop both edges evenly - leaving the best part of it visible, no matter what width of .content
is.
The Solution
Fortunately, a solution is possible. Even better, no extra markup is required.
.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! */
}
这篇关于如何在流体宽度容器中居中裁剪图像 (<img>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!