Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and not interact with the rest of the page. My initial thought was to position the children using JavaScript, like so:

function adjustChildPositions() {
    var ddl = document.getElementById("myDDL");
    var items = ddl.getElementsByTagName("LI");
    var bottom = 0;
    for (var i = 0; i < items.length; i++) {
        items[i].style.top = bottom + 5 + "px";
        bottom += items[i].height;
    }
}

The idea is to have the parent element set to position: relative and each child element set to position: absolute to isolate them from the other content on the page.

However, I suspect that this approach is not straightforward and there may be a way to achieve this using only CSS. Hence, I turn to the experts in search of guidance.

Here is a summary of what I have implemented so far for clarity:

... (remaining content remains unchanged for brevity)

Answer №1

You were so close - all you needed was a wrapper around your ul.

Here are some key points:

  • Selecting an option will automatically close the dropdown. To prevent this, use e.stopPropagation()

  • The dropdown may extend off the bottom of the page. Adjusting the height of the ul and enabling scrolling when open can resolve this issue

  • The dropdown lacks accessibility features

function openDropDown(dropDownList) {
dropDownList.classList.toggle("selecting");
}
* {
transition: 0.3s all linear;
}
html,
body {
margin: 0;
height: 100%;
background-color: #319;
background-image: linear-gradient(45deg, #b0a, #319);
background-image: -webkit-linear-gradient(45deg, #b0a, #319);
overflow: hidden;
}
.primary-content {
height: 100%;
text-align: center;
padding: 15px;
color: #fff;
overflow-y: auto;
display: flex;
flex-direction: column;
align-items: center;
}

/* Dropdown Specific Styles Start Here */
.drop-down {
width: 300px;
height: 3em;
}
.drop-down-list {
position: relative;
list-style-type: none;
padding: 0;
padding-right: 5px;
min-width: 300px;
text-align: left;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.drop-down-list:after {
content: "\21AC";
position: absolute;
top: -5px;
right: 5px;
font-size: 30px;
color: #555;
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.drop-down-list.selecting:after {
-webkit-transform: scaleX(-1) rotate(90deg);
transform: scaleX(-1) rotate(90deg);
}
.drop-down-list.selecting {
max-height: 60%;
position: absolute;
}
.drop-down-list > li {
background-color: rgba(255, 255, 255, 0.95);
color: #555;
padding: 2px;
padding-left: 10px;
margin-bottom: 5px;
border-radius: 5px;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.25);
cursor: pointer;
}
.drop-down-list > li.selected {
background-color: rgba(20, 200, 255, 0.95);
color: #fff;
}
.drop-down-list:not(.selecting) > li.selected {
background-color: rgba(255, 255, 255, 0.95);
color: #555;
}
.drop-down-list:not(.selecting) > li.selected:hover {
background-color: #fff;
}
.drop-down-list:not(.selecting) > li:not(.selected) {
height: 0;
line-height: 0;
font-size: 0;
padding: 0;
margin: 0;
opacity: 0;
}
.drop-down-list > li:hover {
background-color: #fff;
}
.drop-down-list > li.selected:hover {
background-color: #3cf;
}
<div id="primary-content" class="primary-content">
  <p class="lead">Click an option to expand its child elements.</p>
  <div class="drop-down">
    <ul class="drop-down-list" onclick="openDropDown(this);">
      <li>Option 1</li>
      <li>Option 2</li>
      <li>Option 3</li>
      <li class="selected">Option 4</li>
      <li>Option 5</li>
      <li>Option 6</li>
      <li>Option 7</li>
      <li>Option 8</li>
      <li>Option 9</li>
      <li>Option 10</li>
      <li>Option 11</li>
      <li>Option 12</li>
      <li>Option 13</li>
    </ul>
   </div>
<p class="lead">This paragraph serves as content below the dropdown to ensure that expanding the control doesn't disrupt the layout.</p>
</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

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

Position the second line of text to align in MUI

I am facing an issue with aligning the text on the second line. It should match up with the text on the first line. For reference, you can check out the Codesandbox by CLICKING HERE <Card sx={{ maxWidth: 200 }}> <CardMedia component="i ...

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divisio ...

Is the ID selector the quickest method in jQuery and CSS?

Which is the optimal choice in jQuery/javascript for speed? $('#myID .myClass') or $('.myClass') What is the preferred option to utilize in CSS? #myID .myClass{} or .myClass{} In hindsight, I realize my explanation was insuffici ...

ReactJS: The function .useSelector() is not defined

I've been following a tutorial for a while and hit a roadblock trying to understand this. Both metaphorically and literally. On the Dashboard page, I attempted to use useSelector() to access the state of the goalSlice component. This component is ver ...

In ReactJS, one can create a variable and include a map function by first declaring the variable and then using the map function within the component. If you

Having trouble integrating the accordian.js page into the app.js main page for compilation. Need help defining and writing out the function correctly, any suggestions? Below is my code: App.js: How do I incorporate the components from the accordian.js pa ...

What is the process for enabling the experimental-modules option when running an npm package's bin command?

Beginning with Node v8.5.0, the support for ES6 style modules has been introduced. import x from 'x' You can access this feature by running node using the --experimental-modules option, like so: node --experimental-modules test.mjs By utilizi ...

issue with date filtering in query

I'm currently developing a date and time filter for a database. The goal is to query results only within a specific date range selected by the user in an input field. I've written some code, but it seems like something is missing because it' ...

Is there a way to dynamically toggle the visibility of a floating textarea between on and off?

I have my own blog website: Essentially, what I am aiming for is When a user clicks on the search button, a floating semi-transparent textarea window should appear inside the designated rectangle area (as shown in the image, that red orange rectangle). ...

Google Maps GeoCoding consistently relies on the language settings of the browser in use

I have implemented the Google AJAX API loader to retrieve information in German by loading the maps API using this code: google.load("maps", "2", {language : "de"}); Despite trying variations such as deu, ger, de, de_DE, and ...

Prevent background image animation in CSS

I've encountered an issue with a simple button I created that uses two background images for normal and hover states. Upon testing in various browsers, I noticed that the images animate on hover, causing them to slide up and down. I tried eliminating ...

Expanding the size of one div causes the surrounding divs to shift positions

I am currently working on creating a row of divs that expand when hovered over by the mouse. I have managed to achieve this functionality, but now I want the expanding div to cover its neighboring divs partially, without affecting their sizes or moving the ...

The functionality of an AJAX poll is not functioning properly due to issues with the PHP

I am embarking on my first website and project, hoping to see it through to completion. In my room, I have a modest site set up on a Raspberry Pi 2. Users visit this site to cast their votes of 'yes' or 'no'. However, there seems to be ...

ways to clear the float on the right side of an image

So I have two images that I am trying to float, like this: img{ float:left; clear:right; } <img src='http://img1.imgtn.bdimg.com/it/u=1005212286,2432746147&fm=21&gp=0.jpg' alt=''><br> <img src ...

Step-by-Step Guide: Customize the Background Color in an Angular 4 Select Dropdown Based on the Selected Option

I'm facing a challenge in setting the background color of a select element based on the color attribute of its currently selected option. I'm using Angular 4 for this task. An example of what I am attempting to accomplish is shown below: <se ...