Home > database >  Why using CSS display:grid of parent element shows a scroll bar for child element?
Why using CSS display:grid of parent element shows a scroll bar for child element?

Time:04-11

When the content of the inner div is long and needs the scrollbar to be shown, the scroll bar is not showing unless I use display:grid on the parent (.container).

I know I can simply set height of inner-container to 100%. But my question is why setting parent display to grid shows a scroll bar? And is there any proper way to show a scrollbar without setting height of inner-container?

.container {
  display: grid;
  grid-row: 2;
  grid-column: 2;
  height: 100px;
}

.inner-container {
  overflow-style: auto;
  overflow-y: scroll;
}
<div >
  <div >
    <ul>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
    </ul>
  </div>
</div>

CodePudding user response:

both grid and flex will give you scroll bar for a similar reason which is the default stretch alignment. inner-container will get stretched to its parent height due to that alignment so it's like having height:100% then you have your scrollbar because of the overflow: scroll

No other display can do the same because the stretch alignment exits only with flexbox and CSS grid.

If you disable it, it won't happen:

.container {
  display: grid;
  grid-row: 2;
  grid-column: 2;
  height: 100px;
  align-items:start;
}

.inner-container {
  overflow-style: auto;
  overflow-y: scroll;
}
<div >
  <div >
    <ul>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
    </ul>
  </div>
</div>

  • Related