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?
当前回答
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
包含的div本质上是通过隐藏溢出来裁剪图像。
其他回答
谢谢sanchothefat。
我对你的回答有改进的地方。由于裁剪是非常适合每一个图像,这个定义应该在HTML而不是CSS。
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
如果你正在使用Bootstrap,尝试使用{background-size: cover; }对于<div>可能给div一个类说<div class="example" style=url('../your_image.jpeg');>所以它变成 div.example { background-size:封面}
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
我所做的是创建一个服务器端脚本,它将在服务器端调整大小和裁剪图片,这样它就会在互联网上发送更少的数据。
它相当简单,但如果有人感兴趣,我可以挖掘并发布代码(asp.net)