如何在流体宽度容器中裁剪图片(< img>) [英] How to center crop an image (<img>) in fluid width container

查看:269
本文介绍了如何在流体宽度容器中裁剪图片(< img>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果图片的流体宽度(基于百分比)容器太小,无法显示整个图片,如何让图片保持居中?



>



如何将图片置于容器中央



这意味着它应该显示

解决方案

工作时间



您可能有一个容器,其中包含一些内容,例如两个< div> ,每个宽度各为50%,彼此相邻。对于这个例子,我们可以只显示容器的一个子元素:

我们将命名外部矩形 .container ,内部矩形 .content 和图像 img 。只要 .content 始终比 img 更宽,则这种安排是完全正确的。



何时崩溃



由于我们在处理百分比并且可能使用响应式设计,不总是这样。如果 .content img 更薄,则会出现裁剪:



>



问题



如果 img 最有趣的部分在中心,我们需要让浏览器裁剪边缘均匀 - 留下最好的部分可见,无论 .content 的宽度是多少。





解决方案



幸运的是,一个解决方案是可能的。

  .content {
width:90%; / *或任何所需的* /
text-align:center; / *确保图像总是在h-middle * /
overflow:hidden; / *隐藏裁剪部分* /
}

img {
position:relative; / *允许重定位* /
left:100%; / *将图像的整个宽度移动到右边* /
margin-left:-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! */
}

这篇关于如何在流体宽度容器中裁剪图片(&lt; img&gt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆