简体   繁体   中英

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%;
}

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM