Search code examples
cssmobile-safari

Image expanding out of div on iPad mobile Safari


<div class="outer">
    <div class="inner">
        <div class="main">
            <img src="http://placehold.it/180x180">
        </div>
    </div>
</div>

.outer {
    /* Outer Container With Padding */
    background: red;
    padding: 60px;
    max-width: 400px;
}

.inner {
    /* Bottom padding for fluid div with 2:1 ratio */
    padding-bottom: 50%;
    position: relative;
    width: 100%;
}

.main {
    /* container for the image */
    background: green;
    position: absolute;
    height: 100%;
    width: 100%;
}

.main img {
    height: 100%;
    width: 100%;
}

I can't for the life of me figure out why the image is stretching beyond its container div. It works fine in everything except for mobile safari and chrome for iPad. Running the latest version of iOS.

Open below on iPad to see:

http://jsfiddle.net/svja8rgv/3/


Solution

  • You're going to want to set the positioning of the image itself to position: absolute.

    <div class="outer">
        <div class="inner">
            <div class="main">
                <img src="http://placehold.it/180x180">
            </div>
        </div>
    </div>
    
    .outer {
        /* Outer Container With Padding */
        background: red;
        padding: 60px;
        max-width: 400px;
    }
    
    .inner {
        /* Bottom padding for fluid div with 2:1 ratio */
        padding-bottom: 50%;
        position: relative;
        width: 100%;
    }
    
    .main {
        /* container for the image */
        background: green;
        position: absolute;
        height: 100%;
        width: 100%;
    }
    
    .main img {
        position: absolute;
        height: 100%;
        width: 100%;
    }