Dars
Dars

Reputation: 11

How to stop images stretching in Safari when using flex css

2 img elements inside a div. I want the images displayed next to each other rather than stacked, so applied flex. I also want both images to be equal in width and height.

It works perfectly on every browser (chrome, opera, firefox, brave) apart from safari. I've read safari is bugged so stretches the images.

I added align-items: flex-start; which fixes the stretching, but then the height of the 2 images becomes uneven at the bottom.

enter image description here

I've just set a webkit css for now, so height is uneven only on safari and fine on other browsers.

Is there any way around this?

CSS:

.portfolio-box {
    margin-top: 40px;
    display: flex;
    width: 100%;
}

.portfolio-box > * + * {
    margin-left: 4%;
}

.portfolio-box img {
    width: 48%;
    border-radius: 5px;
    margin-bottom: 150px;
}

HTML:

<div class="portfolio-box">
     <img src="./img/portfolio2.jpg" alt="">
     <img src="./img/portfolio3.jpg" alt="">
</div>

Upvotes: 1

Views: 1805

Answers (2)

code and pixels
code and pixels

Reputation: 674

The images (vertically, I'm assuming) stretching is default flexbox behavior, not a Safari bug. I grabbed your code snippets and put them into Codepen - they look the same across Safari (Mac) and Firefox/Chrome (Win10).

I added a few other variations of your code below the 1st bit, but the very last bit I also limited the height of the images. You can see they become distorted again.

You could possibly use "object-fit" on the images like so (or see bottom example in the above linked Codepen):

img {
    height: 100%;
    width: 100%;
    object-fit: cover;
}

However, you can see that the 1st image (the taller one) is cropped.

At the end of the day, if you want the height and width of images to match in a flexbox layout without distortion or cropping, they need to have matching dimensions to begin with.

Upvotes: 2

Hyziu
Hyziu

Reputation: 41

I think that JavaScript may help you. If the only thing that you are missing on is the uneven height of elements on Safari Browser, then you can set equal height of the elements using a simple JavaScript function. This will work on every browser and you won't need to prefix your CSS.

function setEqualHeight() {
    'use strict';
    
    var firstElement        = document.getElementById("first-element");
    var firstElementHeight  = document.getElementById("first-element").clientHeight;

    var secondElement       = document.getElementById("second-element");
    var secondElementHeight = document.getElementById("second-element").clientHeight;

    if (firstElementHeight > secondElementHeight) {
        secondElement.style.height = firstElementHeight + "px";
    } else {
        firstElement.style.height = secondElementHeight + "px";
    }
}

Upvotes: 0

Related Questions