Search code examples
htmlcsscss-grid

How can I ensure that my grid is never smaller than its child


I'm using a grid layout to stack elements in the z-direction. For some reason, if one of the child elements is very wide, it can stick out of the grid element:

#z-stack {
    display: grid;
    border: 5px solid green;
}
#z-stack > * {
    grid-column-start: 1;
    grid-row-start: 1;
}

#wide {
    width: 111vw;
    background: orange;
}

#tall {
    height: 111vh;
}
<div id="z-stack">
    <div id="wide"></div>
    <div id="tall"></div>
</div>

You can see that the green border doesn't go all the way around the orange element, meaning that the child element is wider than the parent element. How can I make the parent element grow large enough to contain all its children?


Solution

  • You can set the min-width property of the grid element to min-width: fit-content.

    #z-stack {
        display: grid;
        border: 5px solid green;
        min-width: fit-content;
    }
    #z-stack > * {
        grid-column-start: 1;
        grid-row-start: 1;
    }
    
    #wide {
        width: 111vw;
        background: orange;
    }
    
    #tall {
        height: 111vh;
    }
    <div id="z-stack">
        <div id="wide"></div>
        <div id="tall"></div>
    </div>