Search code examples
cssflexboxdisplaygrid-layout

How to wrap a div and a img in a display:flex container


EDIT: You need to run the snippet in fullscreen.

I have a display: flex container with div element and other with img inside of it , both of them with 50% width. I want them when resizing below 800px width to be with 100% width of the screen and to wrap one after another on a new lines (flex-wrap) but still remain responsive as they were before the wrapping.

I tried, but I'm doing something wrong - when the screen is below 800px width the img is gaining 100% of the width as it should but the first element is hidden and there is no flex-wrap at all.

#elegantImg{
    max-width: 100%;
    height: auto;
}

.elegant-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.col {
    position: relative;
    width: 50%;
    height: auto;
    overflow: hidden;
}

.background {
    background-color: #F6F4F1;
    height: 100%;
}

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


@media screen and (max-width: 800px) {
    .col {
        width: 100%;
    }
}
        <section>
            <div class="elegant-container">
                <div class="col">
                    <div class="background"></div>
                </div>
                <div class="col">
                    <img id="elegantImg" src="https://i.imgur.com/TVL0phR.png" alt="">
                </div>
            </div>
        </section>

Please, help :)


Solution

  • You can specify the aspect-ratio of the column element to apply height, based on the width. Also, remove the styling by id - it is not needed. Change your code to this:

    .elegant-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
    }
    
    .col {
        position: relative;
        width: 50%;
        aspect-ratio: 1/1;
        overflow: hidden;
    }
    
    .background {
        background-color: #F6F4F1;
        height: 100%;
    }
    
    .col img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    
    @media screen and (max-width: 800px) {
        .col {
            width: 100%;
        }
    }
            <section>
                <div class="elegant-container">
                    <div class="col">
                        <div class="background"></div>
                    </div>
                    <div class="col">
                        <img src="https://i.imgur.com/TVL0phR.png" alt="">
                    </div>
                </div>
            </section>