gpt4 book ai didi

html - 如何使中心裁剪图像响应?

转载 作者:太空狗 更新时间:2023-10-29 13:15:54 25 4
gpt4 key购买 nike

基于 existing answer ,我设法将图像居中裁剪。不过,我无法使中心裁剪图像具有响应性。

问题

当我缩小 Web 浏览器窗口的大小时,中心裁剪图像无法很好地缩小。相反,它保持固定的 heightwidth 并且 spills 超出视口(viewport)。 Fiddle 或许可以更清楚地说明问题.

如何使中心裁剪后的图像很好地缩小?理想情况下,中心裁剪图像将很好地缩小,同时仍被裁剪并保持相似的纵横比。

.centered-container {
max-width: 960px;
margin: auto;
}
.center-cropped-img {
width: 640px;
height: 360px;
overflow: hidden;
margin: 10px auto;
border: 1px red solid;
position: relative;
}
.center-cropped-img img {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
min-height: 100%;
min-width: 100%;
}
<div class="centered-container">
<div class="center-cropped-img">
<img src="http://i.imgur.com/Ag2ZCgz.png" alt="" />
</div>
<div class="center-cropped-img">
<img src="http://i.imgur.com/BQUgmlB.png" alt="" />
</div>
</div>

同样,这是一个 Fiddle这也许比散文更能说明问题。

最佳答案

阅读代码中的注释以获得解释。

JSFiddle

HTML

<div class="container">
<img src="http://i.imgur.com/Ag2ZCgz.png" alt="" />
</div>
<div class="container">
<img src="http://i.imgur.com/BQUgmlB.png" alt="" />
</div>

CSS

/*some basic markup for a flexible container to crop the image*/
.container {
width: 80%;
border: 3px red double;
margin: 50px auto;
padding:0;
overflow: hidden;/*do not show image that is overflowing*/
background-color: yellow;
}
.container img {
display: block;
width: 200%;/** (1 / part of the total image width you want shown)*100% In this example you want to show 50% of the image-width**/
margin-left:-50%;/*move the image to the left, removing that content from view (and making content on the right appear). -0% will show the left side of the image. The negative value of the defined width in the rule before this one + 100% will show you the right side of the image. I guess you can figure the rest out by changing this value.*/
margin-top: -25%;/*changing the top and bottom values is a bit of a pain. After some trial and error (in google chrome) it appears they are based on the width of the image container, not the height (how unusual is that!!!). So putting -100% in this value would (re)move the image up by the px value of the width of the #container div. If you are using css sprites you should avoid setting this value other than 0%.
Alternatively do some math on the original dimensions of the image: -(vertical pixels you want off the image)/(image width)* 100% should work for pixel precision).
The good news is that the image scales with the #container div. So the image grows and shrinks with the container showing the exact same part of the image (and not showing more/less content).*/
margin-bottom:-25%;/*(re)move some of the bottom part of the image. See margin-top for more (works identical)*/
}

关于html - 如何使中心裁剪图像响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26567277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com