skip to Main Content

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?

2

Answers


  1. Instead of display: grid use display: inline-grid.

    inline-grid allows the parent to track the length of the content.

    grid simply takes up the length of the container.

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search