user3189052
user3189052

Reputation: 75

wrap image into div yet maintain aspect ratio

the image flow out the div, I expect it fit within the wrap because I've set width to the div wrapper. The image maybe not the same size for all, so I didn't set the img to a certain fix width to maintain it aspect ratio.

demo link

profile-pic-wrap {
    width:200px;
    height:200px;
    border: 5px solid black;
}
img {
    width:100%;
}

Upvotes: 0

Views: 609

Answers (2)

Joe Conlin
Joe Conlin

Reputation: 5994

Here is the correct code to solve your problem. This will resize any image into the container while maintaing the correct aspect ration.

Also, you should try to avoid background-size: cover because browser support is poor for older browsers.

http://fiddle.jshell.net/293mW/4/

.profile-pic-wrap {
    width:200px;
    height:200px;
    border: 5px solid black;
}
img {
    width:100%;
    max-width: 100%
    height: auto;
}

Upvotes: 0

j08691
j08691

Reputation: 207861

You left the . out of your class. But event with that (http://fiddle.jshell.net/293mW/1/) the image will pop out of the div. You could add overflow:hidden; to the div, but that will crop the image (http://fiddle.jshell.net/pzDVd/).

You probably want to use a background image instead and the background-size: cover; or background-size: contain; rule. See also https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

jsFiddle example (or http://fiddle.jshell.net/Fhnk8/)

.profile-pic-wrap {
    width:200px;
    height:200px;
    border: 5px solid black;
    background-image: url(http://naijaparrot.com/wp-content/uploads/2013/10/mark-zuckerberg-le-fondateur-de-facebook.jpg);
    background-size: cover;
}

Upvotes: 1

Related Questions