HTML - Bootstrap - 如何裁剪图像的中心部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28460844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML - Bootstrap - How to crop the center part of an image
提问by FljpFl0p
I'm creating a website and I want to crop an image to a square image based on the orientation of the image. I'm not really familiar with CSS so I'm not sure how to tackle this problem.
我正在创建一个网站,我想根据图像的方向将图像裁剪为方形图像。我对 CSS 不是很熟悉,所以我不确定如何解决这个问题。
If it's a landscape image (800x500) then I want the cropped image to be like this (500x500):
如果它是横向图像(800x500),那么我希望裁剪后的图像是这样的(500x500):
If it's portrait (400x600) then it should crop out this part (400x400) of the image:
如果是肖像 (400x600),那么它应该裁剪出图像的这一部分 (400x400):
How should I go about to achieve this? Preferably a method I can use along with Bootstrap's "img-responsive" so I can resize the cropped when needed.
我应该如何实现这一目标?最好是一种我可以与 Bootstrap 的“img-responsive”一起使用的方法,这样我就可以在需要时调整裁剪的大小。
Thanks,
谢谢,
采纳答案by állan Fidelis Toledo
@FljpFl0p fix it [jsfiddle][1]
@FljpFl0p 修复它 [jsfiddle][1]
[1]: https://www.bootply.com/92024and there is another answer here How to automatically crop and center an image. Tks!
[1]:https: //www.bootply.com/92024这里还有另一个答案如何自动裁剪和居中图像。太棒了!
If you want it responsive and using bootstrap 4. Try this one:
如果您希望它具有响应性并使用引导程序 4。试试这个:
CSS
CSS
.thumb-post img {
object-fit: none; /* Do not scale the image */
object-position: center; /* Center the image within the element */
width: 100%;
max-height: 250px;
margin-bottom: 1rem;
}
回答by ajib
Not sure if you are pretty limited to a CSS approach only, but a JavaScript approach would help by getting the image's dimension and wrapping it with in a div with overflow:hidden
.
不确定您是否仅限于 CSS 方法,但是 JavaScript 方法会通过获取图像的尺寸并将其包装在带有overflow:hidden
.
$width = $(".box img").css('width');
$height = $(".box img").css('height');
$max = (($width < $height) ? $width : $height);
$(".box").css("width", $max);
$(".box").css("height", $max);
.box {
margin: 5px;
overflow: hidden;
display: flex;
justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img src="https://placehold.it/300x200">
</div>
回答by Jimmy
Add class img-responsive to img tag, which will scale your image and keep width / height ratio. If you are not satisfied with the results I would try using Javascript.
将类 img-responsive 添加到 img 标签,这将缩放您的图像并保持宽度/高度比例。如果您对结果不满意,我会尝试使用 Javascript。