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

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...

Addressing the spacing and alignment issues within the progress bar

I need some help with my Angular app. I am currently working on creating a progress bar, but I am facing some issues with the alignment of the bars. Here is the code snippet that I have used: CSS: .progressbar { position: relative; height: 56px; mar ...

Ways to prevent text from wrapping in CSS

I'm currently in the process of creating a new website and I've encountered an issue with my CSS. It seems that whenever there is a space present, the text inside h2 tags wraps unexpectedly. You can visit the site here. Here's the specific ...

Support for TrueType fonts in web browsersLet me know if you

If I have a custom font in TTF format and want to check if @font-face supports it, what script can I use? What are the available options? ...

What causes the lack of sorting ability in AJAX responses?

I have integrated sorttable.js for table sorting, and my table is updated every 3 seconds with an ajax response. However, the response is not sorted in the manner I expect. Main Page <div id="resDiv"> <table id="myTable1" class="sortable"> ...

AngularJS is failing to update the shared service model

Utilizing AngularJS, my application contains two controllers that share a common service. When triggering an event controlled by the portalController function (specifically the setLang() function), I notice that the model of the applicationController does ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Verification of Email Address Using HTML5

There are claims that with HTML5, there is no longer a need for JavaScript or server-side code to validate user input as a valid email or URL address. I am wondering how I can validate an email after a user enters it and without using JS, how can I displa ...

The variable fails to receive the AJAX response

Trying to retrieve the content of data.dat, I have utilized the following code. Below are the relevant files: main.js function getData() { var result; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Does CSS have a selector that does not include any elements?

Considering the examples below <span id="foo_repeater_bar_0"></span> <span id="foo_repeater_batz_1"></span> I am looking for a CSS selector that will allow me to target only the elements whose id does not include foo_repeater. ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

Place content following a three.js display created within a <div id="mainWindow">

Recently, I created a small Three.js animation and embedded it in my HTML page like this: <div id="mainWindow" class="popup_block"> <!-- JavaScript for simulation --> <script src="../temp/webgl-debug.js"></script> <scri ...

"Verifying the dimensions of the input sizes with the i

It's possible that this question has been asked before on this platform. However, I haven't come across a satisfactory answer yet. How can I adjust the size of inputs in the iCheck library? The current size is too large for my website. Css: .ic ...

The svh/lvh units are experiencing unexpected issues when using Chrome on an iPhone

I'm facing an issue with my hero section that is supposed to take up the full height of the viewport. I recently tried using the new svh/lvh units, which seemed to work fine on desktop and Safari for mobile. However, when testing on Chrome for mobile ...

Reading settings from web.config file in an HTML page

Currently working with ASP.NET 3.5 web forms. I've recently saved the path of my website in the web.config file under the key "CommonPath". I have a basic static HTML page that I would like to utilize this key on. Any suggestions on how to achieve ...

What is the process of adding information to a database from a table using JSP?

Is it possible to store data into a database using JSP? Here is the code I have written, can you please help me find and correct any errors in it? My goal is to fetch data from form fields in a JSP page and store it into a database. Database name: test T ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Dynamically pass specific outputs from multiple SQL queries to a form

The query is functioning properly, returning a table with the associated data in rows. I am looking to have a button displayed with each row that triggers a function specific to that row when clicked. Currently, the function works manually by inputting the ...

Force the page to refresh if the user navigates back using the browser's back button

Similar Question: Cross-browser onload event and the Back button I am looking for a way to automatically refresh a view or page when a user navigates back to it using the browser's back button. Any suggestions? ...