htmlcss

Is there an easy way to make an element fill its parent's width when the parent is overflowing?


There is a container div that is overflowing (scrolling) horizontally based on dynamic content. I want to put a div inside it that fills the entire width of the container. Using the CSS property width: 100% does not work here, because it does not take into account the overflow.

This is a minimal example illustrating the problem:

.overflowing-container {
  overflow-x: auto
}

.unknown-width {
  width: 130%; /* this is unknown, determined by content */
  background-color: yellow;
  padding: 20px;
}

.too-narrow {
  width: 100%;
  background-color: lightblue;
  padding: 20px;
}
<div class="overflowing-container">
  <div class="unknown-width">
    This div is of unknown width. It makes the parent overflow.
  </div>
  <div class="too-narrow">
    This div should fill its overflowing parent, but "width: 100%" is only the viewport width in this context. When you scroll to the right, this stops.
  </div>
</div>

Is there a solution using only CSS? Or do I have to use JavaScript to query the parent width?


Solution

  • If I understood correctly, what you might need is this:

    .overflowing-container {
      overflow-x: auto;
      
      /* Added properties */
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
    }
    
    .unknown-width {
      width: 130%;
      background-color: yellow;
      padding: 20px;
    }
    
    .too-narrow {
      /* width: 100%; Removed property */
    
      background-color: lightblue;
      padding: 20px;
    }
    <div class="overflowing-container">
      <div class="unknown-width">
        This div is of unknown width. It makes the parent overflow.
      </div>
      <div class="too-narrow">
        This div should fill its overflowing parent, but "width: 100%" is only the viewport width in this context. When you scroll to the right, this stops.
      </div>
    </div>

    Using flex to position elements in column direction and then flex-wrap to wrap elements. Since it's trying to wrap elements it will also try to fill all available width space. That space is width of the element with the biggest width space. With removing width: 100% you ensure that width is not bounded to viewport width. Also, every other flex element that you might add will also fill all available width space.