Search code examples
csscss-grid

Overlapping Grid Elements: 2nd div fails to load


Both divs display correctly alone, but if both img-1 and img-2 divs are both in the container, the second div disappears.

HTML:

<div class="body-background">
    <div class="background-img-1"></div>
    <div class="background-img-2"></div>
</div>

CSS

.body-background {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    grid-template-rows: 1fr;
    width: 100%;
    height: 100%;
}
.background-img-1 {
    background: red;
    grid-column: 1 / 3; 
}
.background-img-2 {
    background: blue;
    grid-column: 2 / 4;
}

Shouldn't the boxes overlap normally?


Solution

  • Give both background divs a grid-row: 1 property (which becomes grid-row: 1 / 2). I don't think the browser likes having to give it implicitly to two overlapping cells.

    .body-background {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        grid-template-rows: 1fr;
        width: 100vw;
        height: 100vh;
    }
    .background-img-1 {
        background-color: red;
        grid-column: 1 / 3;
        grid-row: 1;
    }
    
    .background-img-2 {
        background-color: blue;
        grid-column: 2 / 4;
        grid-row: 1;
    }
    <div class="body-background">
        <div class="background-img-1"></div>
        <div class="background-img-2"></div>
    </div>