简体   繁体   中英

auto sizing image in div with css works only with width, not height

I'm trying to auto-fit an image to it's container while maintaining its aspect ratio using css. The image has a bit too much height to fit on a phone screen. I'm using this css, which seems like it should work, but it only resizes the image for width changes, not height.

body {
    background-color: #0055AF;
    overflow-x: visible;
}

#new_site_teaser {
    width: 405px;
    height: 683px;
    margin: 0 auto;
    max-width: 100%;
    max-height: 100%;
}

#new_site_teaser img{
    max-width: 100%;
    max-height: 100%;
    margin: 0 auto;
}

Here is a fiddle: http://jsfiddle.net/7m50rg74/

Any help would be appreciated.

change the #new_site_teaser width to % and define and height and width for the parents (body & html in this case); it'll adjust to each device. It's much better than using pixels. See changes: http://jsfiddle.net/7m50rg74/16/

Ensure you have a meta viewport.

add this to your head tag, if not. This defines a viewport for your site to be seen on, in this case it'll adjust the width automatically for every device and have a scale = 1 (zoom).

<meta name="viewport" content="width=device-width, initial-scale=1"> 

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