Crop image using object-fit
You can crop an image with the tag img
using the object-fit
as follows:
.objectImage {
width: 600px;
height: 120px;
object-fit: cover;
object-position: center;
}
.imagemNormal {
width: 600px;
height: 120px;
}
<div class="imagem">
<span>object-fit: cover; (imagem recortada)</span>
<img class="objectImage" src="http://i.stack.imgur.com/gL1sB.jpg">
</div>
<div class="imagem">
<span>imagem não recortada (altura da imagem encolhe) </span>
<img class="imagemNormal" src="http://i.stack.imgur.com/gL1sB.jpg">
</div>
Nowadays all browsers support the object-fit
except for Internet Explorer.
More information about the Object-fit property at the following links:
Crop image using a container with the properties Overflow
and Position
.imagem-wrapper {
width: 600px;
height: 120px;
overflow: hidden;
position: relative; /* Para fazer que a imagem com position-absolute respeite a sua posição consoante este selector, ou evitar que saia do mesmo */
}
.imagem {
width: 600px;
/* código abaixo centra a imagem ao centro */
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
<div class="imagem-wrapper">
<img class="imagem" src="http://i.stack.imgur.com/gL1sB.jpg">
</div>
Crop image using image as background
If you are using the image as background-image
, you can also do it using the property background-size: cover;
.
.imagemBg {
width: 600px;
height: 120px;
background: url(http://i.stack.imgur.com/gL1sB.jpg) center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<div class="imagemBg"></div>
Alternative
Alternatively, if you are looking to crop an image with several measures prepared, you can always use plugins, such as jQuery you have the resizeAndCrop.
There are also other plugins in PHP like Timthumb, but this is no longer advisable due to security issues. But you can always Google plugins to your language preference, PHP/Javascript etc to find what’s best and fit your needs.