How to show a dropdown menu outside a parent element with overflow: auto in CSS?

Viewed 1824

I have tried a lot of things and searched online but I cannot figure out the solution to this problem.

I have a div container which has a max-height, min-height and also overflow: auto. When the inner content is larger than the max-height, a scrollbar appears as expected. But, inside the content there is a dropdown, which when clicked, the menu expands, and instead of being displayed outside the parent container, it is like changing the inner content height.

The only solution I found online and made sense to me, is to wrap the container to div with relative positioning and make the dropdown absolute, but there is a big drawback now, the dropdown stays fixed on scroll, as it is absolute positioned relative to the wrapper and not the content. Is there any common way to fix this or any other solution ?

I didn't post any code because I do not want the answer to rely on my code. I just want a minimal example if possible with these properties:

  1. Container has a max-height
  2. If content is larger than the container's max-height then the container should display a scrollbar.
  3. The content has a dropdown which should scroll with every other element of the content.
  4. The menu options of the dropdown element are escaping the container / are displayed outside the boundaries of the container.
1 Answers

To illustrate on my comments on the question, here's an MCVE:

.scroll-container {
  border: 3px dashed #eee;
  height: 400px;
  padding: 10px;
  overflow: auto;
  width: 400px;
}

.content {
  background-color: #f0f0f0;
  height: 600px;
  position: relative;
}

.dropdown {
  background-color: orange;
  position: absolute;
  height: 300px;
  width: 300px;
  left: 300px;
}
<div class="scroll-container">
  <div class="content">
    <div class="dropdown"></div>
  </div>
</div>

As you can see, with absolute positioning based on the relative position of div.content the orange div.dropdown creates a horizontal overflow, which is what you don't want. To fix this scenario, you need to remove position: relative from div.content and use transform: translateX(300px); instead of left: 300px;:

.scroll-container {
  border: 3px dashed #eee;
  height: 400px;
  padding: 10px;
  overflow: auto;
  width: 400px;
}

.content {
  background-color: #f0f0f0;
  height: 600px;
}

.dropdown {
  background-color: orange;
  position: absolute;
  height: 300px;
  width: 300px;
  transform: translateX(300px);
}
<div class="scroll-container">
  <div class="content">
    <div class="dropdown"></div>
  </div>
</div>

Related