CSS 显示调整大小和裁剪的图像 [英] CSS Display an Image Resized and Cropped
问题描述
我想显示来自具有特定宽度和高度的 URL 的图像,即使它具有不同的大小比例.所以我想调整大小(保持比例),然后将图像剪切到我想要的大小.
我可以使用 html img
属性调整大小,我可以使用 background-image
进行剪切.
我怎样才能做到这两点?
示例:
这张图片:
具有 800x600
像素大小,我想显示为 200x100
像素的图像
使用 img
我可以调整图像的大小 200x150px
:
这给了我这个:
<img style="width: 200px; height: 150px;"src="https://i.stack.imgur.com/wPh0S.jpg">
使用 background-image
我可以剪切图像 200x100
像素.
给我:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); 宽度:200px; 高度:100px; background-position:center;"> </div>
我怎样才能做到这两点?
调整图像大小,然后将其剪成我想要的大小?
解决方案 您可以结合使用这两种方法,例如.
.crop {宽度:200px;高度:150px;溢出:隐藏;}.crop img {宽度:400px;高度:300px;边距:-75px 0 0 -100px;}
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="唐老鸭">
您可以使用负 margin
在
内移动图像.I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.
I can resize with html img
property and I can cut with background-image
.
How can I do both?
Example:
This image:
Has the size 800x600
pixels and I want to show like an image of 200x100
pixels
With img
I can resize the image 200x150px
:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
And with background-image
I can cut the image 200x100
pixels.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
解决方案 You could use a combination of both methods eg.
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
<div class="crop">
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
</div>
You can use negative margin
to move the image around within the <div/>
.
这篇关于CSS 显示调整大小和裁剪的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文