Search code examples
htmlcssgoogle-chromefirefoxflexbox

There is different behavior between Firefox and Chrome when using flex:1 on an img


There is different behavior between Firefox and Chrome when using flex:1 on an img.

Code pen demonstrating the behavior.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="./styles.css">
        <script src="./script.js" defer></script>
    </head>
    <body>
        <section class="container">
            <div class="flex"> <h2>Something for the title</h2>
            <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Odio, totam?</p>
            </div>
    
            <img class="flex box-img" src="./Images/blender_render-1280x720_1.jpg" alt="">
        </section>
    </body>
    </html>

    .box-img{
        width: 100%;
        background-color: red;
        display: block;
    }
    .container{
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 1rem;
    }
    .flex{
        flex:1;
        background-color: brown;
    }

If you open the codepen in Firefox and Chrome, you will notice that in Firefox the ratio is 50%/50%. and in Chrome, the img occupies the majority of the screen.

I was after the behavior of Firefox, where the flex items share the same space on the viewport.

I found a workaround by enveloping the img in a div and applying the flex to the div instead of the img. I would like to know if this behavior is normal. Is it because the img element is a replaced element and doesn't conform to the normal behavior of an element?

Thanks for your time in advance.


Solution

  • The behavior you're seeing is related to how browsers handle the intrinsic sizing of replaced elements within a flex container.

    In Firefox, the image is treated as if it has an intrinsic aspect ratio of 1:1 by default. As a result, when you use flex: 1 on the container, it distributes the space evenly between the text and the image.

    In Chrome, the image is taking its intrinsic size into account differently, and it appears to take up more space, causing the uneven distribution of space between the text and the image.

    By wrapping the image in a div container and applying the flex property to the div, you have more control over how the container flexes, and you can achieve the desired layout.