What is the best way to place this dropdown in a fixed position within a parent element with overflow scrolling

I am facing an issue with a dropdown menu inside a parent div. The parent div has a fixed height and is set to overflow: auto. My goal is to have the menu extend beyond the boundaries of the parent when opened, but currently it just increases the height of the parent.

You can view a minimal test case on CodePen, or refer to the code below:

HTML

<div class="parent">
    <div class="dropdown">
        <button id="btn" class="btn" type="button">Click me</button>
        <div id="menu" class="menu">I should protrude outside the parent, but instead I trigger scrolling within the parent</div>
    </div>
</div>

SCSS

.parent {
    height: 3rem;
    padding: 0.25rem;
    background-color: #f5f5f5;
    overflow: auto;
    text-align: center
}
.btn {
    font-size: 1.2rem;
}
.dropdown {
    display: inline-block;
    position: relative;
}
.menu {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    background-color: white;
    border: 1px solid #eee;
    padding: 0.5rem;
    &.show {
        display: block;
    }
}

(The JavaScript simply toggles the show class on the dropdown and is not relevant to this issue.)

I have tried wrapping the dropdown in another div and experimenting with various overflow values on both the dropdown and parent elements without success. I prefer not to resort to moving the menu outside of the parent and positioning it through JavaScript, as I believe there must be a CSS solution available.

If anyone has any insights or solutions to this problem, they would be greatly appreciated!

*Note that it is crucial for the dropdown to remain in the normal document flow, as multiple instances may appear one after the other within the parent div.

Answer №1

Here's a clever little trick you can try out. It may not be the conventional way of doing things, but it gets the job done.

Keep in mind that when scrolling, the menu will not move along with the page. You'll need to add code to detect scroll events on the document and adjust the menu position accordingly.

document.getElementById('btn').onclick = function openMenu() {

  var btn = document.getElementById('btn');
  
  var top = btn.offsetTop;
  var left = btn.offsetLeft;
  var height = btn.offsetHeight;
  
  
  var menu = document.getElementById('menu');
  menu.style.top = top + height +'px';
  menu.style.left = left + 'px';
  
  menu.classList.toggle('show');
};
.parent {
  height: 3rem;
  padding: 0.25rem;
  background-color: #f5f5f5;
  overflow: auto;
}

.btn {
  font-size: 1.2rem;
}

.dropdown {
  display: inline-block;
}

.menu {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  max-width: 100px;
  background-color: white;
  border: 1px solid #eee;
  padding: 0.5rem;
}
.menu.show {
  display: block;
}
<div class="parent">
  <span>The button needs to stay within the document flow to work well with other elements in the parent.</span>
  <div class="dropdown">
    <button id="btn" class="btn" type="button">Click me</button>
    <div id="menu" class="menu">I'm supposed to stick out of the parent, but I end up making the parent scroll instead.</div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...

How do I efficiently render multiple form field components in React CSS when two of them have different flex directions?

I need to find a way to dynamically iterate through multiple input components. All inputs follow the same style pattern except for 'first name' and 'last name', which should be aligned in one row with different widths. <div style={{f ...

Is there a way to make Chrome ask to save a password within an HTML form?

I'm having trouble getting a basic email/password HTML form to prompt Chrome to save the password. Despite following examples, it's not working for me. Here is my code: <form name="loginForm" action=""> E-Mail:<br><input ...

Dividing Trapezoid Shapes, Cropping Background Images

I am attempting to design a website layout with trapezoid shapes similar to the attached image. Each section should have a background image that fills the background with cover or a similar effect. I successfully created the first section (dark blue) usin ...

Working with radio buttons in a loop using PHP

I am facing an issue with a loop that iterates 3 times. In the loop, there's an HTML form containing radio buttons and I am processing the input using PHP. However, when echoing the form data, it does not display the correct values. Is there something ...

Interacting with JQuery UI Button causes it to shift position on mouseover

In my table, there are two large cells. The left cell contains two drop-downs and a JQuery UI button that is causing trouble, while the right cell displays a list generated from an AJAX database query. As the list grows longer, the button gradually moves u ...

Getting the Title value from Selenium in Python: A guide

Can someone provide guidance on how to retrieve the title value from this element using Selenium? I have tried the following code but it is returning an empty string. items = driver.find_elements_by_tag_name("li") for item in items: followe ...

Images in assets folder are not showing up in Vue Bootstrap

I'm attempting to showcase an image similar to the example provided in this guide Below is the code I am using: <template> <b-container fluid class="p-4 bg-dark"> <b-row> <b-col> <b-img rounded="ci ...

Ways to update the color of the mat-dialog-title using the material theme

Currently, I am utilizing the Angular Material Dialog and have been attempting to dynamically change the title color of the dialog based on the material theme. <h1 mat-dialog-title color="primary">{{ title }}</h1> Even though setting ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Does the zoom value in the HTML file adjust when I zoom in or out on the Google Map?

I'm uncertain if my question is sufficiently clear. Here's my dilemma: I've been utilizing the gmplot module in Python and I'm interested in adjusting the grids to be scalable based on the zoom level of the Google Map. However, being u ...

Merging backend code (Java and Python) into HTML for seamless integration

While I have a solid background in back-end coding languages like Java and Python, the task at hand requires integrating this code into a website. The backend code comprises various methods and classes to encrypt text messages using encryption techniques ...

Orders in WooCommerce are being mysteriously created with no information provided and stuck in a pending payment state

Are you experiencing the issue of blank orders being generated in WooCommerce with no details and a pending payment status? I am utilizing the WooCommerce plugin along with the Elavon payment gateway, and although everything seems to be set up correctly, t ...

Utilizing CSS transitions to smoothly adjust the width of an element until it completely fills the container div in ReactJS

import React from 'react'; import PropTypes from 'prop-types'; import SearchIcon from '@material-ui/icons/Search'; import InputBase from '@material-ui/core/InputBase'; import { AccountCircle } from '@material-ui ...

A guide on using Beautiful Soup to retrieve all text elements from a specific class

This is my custom code snippet: # -*- coding: utf-8 -*- from time import sleep import requests from bs4 import BeautifulSoup def get_all_coins(): response = requests.get("https://coinmarketcap.com/") soup = BeautifulSoup(response.content, 'ht ...

Using jQuery to add HTML elements before the content of a list

I'm facing a challenge in dynamically adding new elements to my list. Through ajax, I retrieve HTML data from my database and aim to iterate through each new <li> element to gradually prepend them to the top of the list. This is the snippet of ...

Having trouble locating elements with Selenium in Java?

I've been struggling to locate a particular WebElement using Selenium's API. I attempted to use a wildcard to capture all elements on the page and then iterated through them, but I'm still unable to locate the desired element. Could it possi ...

I am looking to set an HTML file as the homepage for my Next.js project

Is there a way in next.js to render a normal .html file (index.html) when someone visits my root directory at "https://example.com/"? I have researched and edited my config file as shown below, /** @type {import('next').NextConfig} */ const next ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (where A is the cata ...

What is causing the action button in my MUI snackbar to occupy an additional line?

I'm currently learning how to use MUI and I'm struggling with a specific issue. The close button in my code is appearing on a separate line, but I want it to be on the same line as the word "again". I've tried experimenting with absolute pos ...