Baptiste Arnaud Baptiste Arnaud - 8 months ago 17
HTML Question

CSS resize an image and keep the native ratio

What i'm trying to do here, is to crop an image to replace white spaces of my div:

<div id="profilepicture" style='background:url()'>
<img src="utilisateurs/pp/<?php echo $userinfo['photoP']; ?>">
</div>


And here the stylesheet related to this:

#profilepicture{
height: 200px;
width: 200px;
box-shadow: 1px 1px 2px;
display: flex;
}
#profilepicture img{
width: 100%;
height: auto;
margin: auto;
}


Here is what it gives me :

image1

I just want to crop left and right of the photo and zoom at the center to not have white spaces anymore !

Edit:

If i do

width: auto;
height: 100%;


it gives me this :

image2

Now i just want it to be centered!

Any ideas ?

Answer

Center it, add a negative margin and hide the overflow:

#profilepicture{
    height: 200px;
    width: 200px;
    box-shadow: 1px 1px 2px;
    display: flex;
    text-align:center;
    overflow:hidden;
}
#profilepicture img{
    width: auto;
    height: 100%;
    margin: 0 -50%;
}
<div id="profilepicture">
    <img src="http://lorempixel.com/400/200/">
</div>
Here's what it looks like without the container:
<img src="http://lorempixel.com/400/200/">