问题
I've set an image to max-height:100%;
of the browser window (with a small padding at the bottom), centred on the page. Currently, I'm having problems keeping the aspect ratio of the image from squashing when the browser is resized (interestingly it shows at the correct aspect ratio when refreshed after a resize).
I've set up an example in codepen. Would appreciate any advice on how to keep the ratio correct.
http://cdpn.io/sHJhl
UPDATE 18/08: I've updated the code in the copepen above. It's now working in all browsers except Chrome, which distorts the image when the browser is resized. Oddly it resizes fine in Chrome when the codepen is in edit mode. I've tested the code from the codepen in my development site and it shows the same issue, so it's definitely not a codepen quirk. Hoping someone can help on this one.
FURTHER UPDATE 18/08: Solved this issue with Chrome by adding max-width:100%
, see answer below.
回答1:
Solved this issue. The image needed max-width:100%;
as well as max-height:100%; width:auto;
to work in Chrome. I've updated the codepen to show the full working code: http://cdpn.io/sHJhl
回答2:
Image's parent element .photo-bkg
doesn't have any width set, so add it a width: 100%;
.photo-bkg { height:100%; width: 100%; }
That should do the trick.
回答3:
You want to achieve a full page background right?
This worked for me:
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
source: http://css-tricks.com/perfect-full-page-background-image/
来源:https://stackoverflow.com/questions/18252469/retain-aspect-ratio-for-full-height-responsive-image-in-chrome