htmlcsscss-positionabsolute

How to make my absolute cover the whole container with overflow scroll?


I have a container (position: relative) with limited height (in my HTML it's limited by a flex box so I actually don't have the 200px as in the below code shows). It has the content that determines its width and height. Above the content, I have an absolute cover with a background to partially cover the content.

However, when the content overflows, and scrollbars appear, the .cover element does not stretch out. I have tried the following:

None of the above stretch the .cover to match the content. Is it possible?

p {
  width: 2000px; /* Simulating a wide content */
  height: 300px;
  background: cornflowerblue;
  margin: 0;
}

.my-container {
  position: relative;
  overflow: auto;  
  height: 200px; /* Simulating limited space */
  border: 1px solid red;
}

.my-container .cover {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  background: rgba(0,0,0,.8);
  /* I have tried each of these: */
  /*height: 100%;*/
  /*bottom: 0;*/
  min-height: 100%;
  bottom: auto;      
}

.my-container .cover span {
  background: white;
  padding: 1rem;
  margin: 1rem;
}
<div class="my-container">
  <div>
    <p>Very long text line or very wide image.</p>
  </div>
  
  <div class="cover">
    <span class="cover-content">Hello</span>
  </div>
</div>


Solution

  • Thanks to "pier farrugia"'s comment, I realized I could make a scrolling container separate from the cover parent. So I just need to add another wrapper:

    .scrolling-container {
      overflow: auto;  
      height: 200px; /* Simulating limited space */
      border: 1px solid red;
    }
    
    p {
      width: 2000px; /* Simulating a wide content */
      height: 300px;
      background: cornflowerblue;
      margin: 0;
    }
    
    .my-container {
      position: relative;
      width: fit-content; /* This is needed to expand the width to match content */
    }
    
    .my-container .cover {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,.8);     
    }
    
    .my-container .cover span {
      background: white;
      padding: 1rem;
      margin: 1rem;
    }
    <div class="scrolling-container">
      <div class="my-container">
        <div>
          <p>Very long text line or very wide image.</p>
        </div>
    
        <div class="cover">
          <span class="cover-content">Hello</span>
        </div>
      </div>
    </div>