Search code examples
htmlcsslayoutflexboxcss-grid

How to create a two column layout with equal width and height in HTML and CSS


I'm trying to create a two column layout where the left side is a div full of text, and the right side is a div with an image. They should be centered in the container, and they should both have an equal width and height, where the right div's width and height will match the left div's. The image attached to this thread shows my desired effect. I've tried numerous things, with my best guess being:

.container {
    display: flex;
    justify-content: center;
    align-items: stretch;
}

.left-div {
    flex: 1;

    /* not relevant but i will still include it for accurate context */
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.right-div {
    flex: 1;
}

.right-div img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
<div class="container">
    <div class="left-div">
        <p>Some filler text that will cause it to have a width and height that the right div needs to meet</p>
    </div>

    <div class="right-div">
        <img src="https://picsum.photos/id/522/536/354" />
    </div>
</div>

but it did not work, as the image just stretched to the maximum height while retaining its aspect ratio . I don't know how to create this "dependency" with CSS. If I could theoretically set flex: 1 for both the row and column direction, I think that would work, but due to I would need to format the html to get this layout, I wouldn't be able to include both divs as children to two divs. I think it should be achievable with some flexbox or CSS grid magic, though.

Thank you so much for the help!


Solution

  • With inspiration from @Kosh's answer, I solved it with the following code in case anybody finds this thread wondering the same thing:

    .container {
        display: flex;
        justify-content: center;
    }
    
    .left-div {
        flex: 1;
    
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }
    
    .right-div {
        position: relative;
    
        flex: 1;
    }
    
    .right-div img {
        position: absolute;
    
        width: 100%;
        height: 100%;
    
        object-fit: cover;
    }
    <div class="container">
        <div class="left-div">
            <p>Some filler text that will cause it to have a width and height that the right div needs to meet</p>
        </div>
    
        <div class="right-div">
            <img src="https://picsum.photos/id/522/536/354" />
        </div>
    </div>