Forcing aspect ratio with CSS doesn't work on

2019-05-23 14:08发布

问题:

The following code works well in Firefox and Chrome, but doesn't in Safari (tested on Mac and iPad): http://jsfiddle.net/eFd87/.

<div id="wrapper">
    <div id="content">
        <img src="http://farm3.staticflickr.com/2783/4106818782_cc6610db2c.jpg">        
    </div>
</div>

#wrapper {
    position: relative;
    padding-bottom: 33.33%; /* Set ratio here */
    height: 0;
}
#content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: green;
    text-align: center;
}
#content img {
    max-height: 100%;
}​

The goal is to have a wrapper div keep a fixed aspect ratio (in my web application it is a carousel), and the image inside it resize to fit in the div (and center).

On Safari the image doesn't display because of the height: 0 (which will give a height of 0 for the img). With height: 100% the image display but doesn't fit the div (it overflows).

Do you see any solution for this problem? I've been on this for hours...

回答1:

This isn't exactly a great answer to your question but it's an answer nonetheless.

I very much doubt it is possible to do this using a CSS only approach because as far as I know (I'm happy to be corrected on this) there is no way to perform calculations based on the of another css property. So width: height * 1.3; for example isn't possible. You can't use % either because that's a percentage of the parent, not of its self.

The way you are currently looking at involving bottom padding won't work reliably either, it will work on your screen however if someone else screen has a different aspect ratio or they have lots of tool bars changing the aspect ratio of the browser window then the aspect ratio will be wrong. % is of the parent which unless you can guarantee the size of you cannot really use.

So far as I can tell your only option on this is javascript. the most obvious and my recommendation would be jQuery or some other framework to calculate and explicitly set height based on width. Don't forget to listen for browser window resizing though.



回答2:

Width 100% and Height auto worked for me on Safari. Initially, i was using 100% for both w and h which works fine on FF but failed on Safari.

.stretch {
  width: 100%;
  height: auto;
}

HTML:

<div>
    <img src="images/someimg.jpg" class="stretch" alt="" />
</div>

And oh, I've used Bootstrap which adds this to all elements.

*, *:before, *:after {
  -moz-box-sizing: border-box;
}