Home > Software engineering >  CSS Layout Overflow Scroll only in Div
CSS Layout Overflow Scroll only in Div

Time:03-08

I can't seem to get this page layout to work for me. I want the yellow div to be scrollable, however not show past the red div. Setting the page overflow to hidden disables scrolling altogether.

Edit: To clarify, I want the orange highlight to cover the full width in the overflow.

.page {
  background-color: aqua;
  padding: 0 32px;
  height: 300px;
}

.layout {
  background-color: red;
  margin: 0 32px;
  padding: 16px 32px;
  height: 200px;
}

.container {
  background-color: yellow;
  margin: 0 -32px;
  padding: 16px 32px;
  
  white-space: nowrap;
  overflow: scroll;
  display: inline-block;
}

.highlight {
  background-color: orange;
  margin: 0 -32px;
  padding: 0 32px;
}
<div >
  <div >
    <p>
      Some Text
    </p>
    <div >
      <div >Testline1</div>
      <div >Testline1</div>
      <div >Testline1</div>
      <div >
        Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow
        Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow
      </div>
    </div>
  </div>
</div>

Another edit: A big factor for my struggle and confusion was that I'm using tailwind and tailwind applies this css rule on the base:

*,
::before,
::after {
  box-sizing: border-box;
}

This had the effect that the yellow box was always too short.. Adding

.container {
  /* ... */
  box-sizing: content-box;
}

did the trick

CodePudding user response:

The container has not a defined width or height. as such the width and height will be calculated to fit-content. An overflow only can occure if the height/width of the container is smaller then the content.

To fix your issue you just need to add width: 100% to the container to fill out the parents width.

.page {
  background-color: aqua;
  padding: 0 32px;
  height: 300px;
}

.layout {
  background-color: red;
  margin: 0 32px;
  padding: 16px 32px;
  height: 200px;
}

.container {
  background-color: yellow;
  margin: 0 -32px;
  padding: 16px 32px;
  
  white-space: nowrap;
  overflow: scroll;
  display: inline-block;
  width: 100%;
}

.highlight {
  background-color: orange;
  margin: 0 -32px;
  padding: 0 32px;
  width: fit-content;
}
<div >
  <div >
    <p>
      Some Text
    </p>
    <div >
      <div >Testline1</div>
      <div >Testline1</div>
      <div >Testline1</div>
      <div >
        Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow
        Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow Overflow
      </div>
    </div>
  </div>
</div>

  • Related