Adjusting the size of <nav> element to accommodate its child elements

I've exhausted all possible CSS solutions today in an attempt to make my parent nav tag home-main-nav-menu resize based on its children and grandchildren, but it just won't cooperate. If anyone could provide a clear explanation on how to solve this issue, I would greatly appreciate it. Moreover, an explanation as to why elements don't naturally expand to accommodate their child content would be incredibly helpful. Thank you! [refer to the image and CSS for more details]

$(document).ready(function(){
                $('.main-ul').children('li').on('click', function() {
                    $(this).children('ul').slideToggle('slow');
               });
            });
.home-main-nav-menu{
              border-style: double;
              border-color: cyan;
            }
            .A{
              display: inline-block;
              text-align: center;
              padding-left: 5px;
              margin-right: 10px;
              border-style: double;
              border-color: purple;
            }
            .B{
              list-style-type: none;
              text-align: left;
              margin-left: -40.5px;
            }
            .A > ul {
              display: none;
            }
            .main-ul{
              border-style: double;
              border-color: green;
              width: 95.5%;
              margin-left: -3px;
            }
            ul{
              text-align: center;
              position: absolute;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <nav class = "home-main-nav-menu">
                <ul class = "main-ul">
                  <li class = "A"><a href = "#/">a</a></li>
                  <li class = "A"><a href = "#/">b</a>
                    <ul>
                      <li class = "B"><a href = "#/">c</a></li>
                      <li class = "B"><a href = "#/">d</a></li>
                    </ul>
                  </li>
                  <li class = "A"><a href = "#/">e</a></li>
                  <li class = "A"><a href = "#/">f</a>
                  <ul>
                    <li class = "B"><a href = "#/">f</a></li>
                    <li class = "B"><a href = "#/">g</a></li>
                  </ul>
                </li>
                  <li class = "A"><a href = "#/">h</a>
                  <ul>
                    <li class = "B"><a href = "#/">i</a></li>
                    <li class = "B"><a href = "#/">j</a></li>
                  </ul>
                 </li>
                  <li class = "A"><a href = "#/">k</a>
                  <ul>
                    <li class = "B"><a href = "#/">l</a></li>
                    <li class = "B"><a href = "#/">m</a></li>
                  </ul>
                  </li>
                </ul>
            </nav>

View the color map in the CSS

Answer №1

The issue lies within your class definition:

ul{
  text-align: center;
  position: absolute;
}

This code snippet is setting all the ul elements to have an absolute positioning, taking them out of the regular document flow and creating a separate layer for these elements. This causes the nav to be disconnected from its child ul elements, even though they are structured together in the HTML.

To address this problem, you can modify the code as follows:

ul{
  text-align: center;
  position: relative;
}

By changing the positioning to relative, the ul elements are still taken out of the document flow but remain in their original positions within the main document flow. The specific positioning is not defined, allowing the elements to maintain their layout integrity within the parent container.

According to MDN:

absolute

The element is removed from the normal document flow; no space is created for the element in the page layout. Instead, it is positioned relative to its closest positioned ancestor if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. This value creates a new stacking context when the value of z-index is not auto. Absolutely positioned boxes can have margins, and they do not collapse with any other margins.

relative

The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. This value creates a new stacking context when the value of z-index is not auto. The effect of relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.

In addition, removing the line:

width: 95.5%;

from the .main-ul class will prevent the ul elements from overflowing their parent container.

$(document).ready(function(){
    $('.main-ul').children('li').on('click', function() {
     $(this).children('ul').slideToggle('slow');
   });
});
.home-main-nav-menu{
  border-style: double;
  border-color: cyan;
}
.A{
  display: inline-block;
  text-align: center;
  padding-left: 5px;
  margin-right: 10px;
  border-style: double;
  border-color: purple;
}

.B{
  list-style-type: none;
  text-align: left;
  margin-left: -40.5px;
}
.A > ul {
  display: none;
}
.main-ul{
  border-style: double;
  border-color: green;
  margin-left: -3px;
}

ul{
  text-align: center;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class = "home-main-nav-menu">
    <ul class = "main-ul">
      <li class = "A"><a href = "#/">a</a></li>
      <li class = "A"><a href = "#/">b</a>
        <ul>
          <li class = "B"><a href = "#/">c</a></li>
          <li class = "B"><a href = "#/">d</a></li>
        </ul>
      </li>
      <li class = "A"><a href = "#/">e</a></li>
      <li class = "A"><a href = "#/">f</a>
      <ul>
        <li class = "B"><a href = "#/">f</a></li>
        <li class = "B"><a href = "#/">g</a></li>
      </ul>
    </li>
      <li class = "A"><a href = "#/">h</a>
      <ul>
        <li class = "B"><a href = "#/">i</a></li>
        <li class = "B"><a href = "#/">j</a></li>
      </ul>
     </li>
      <li class = "A"><a href = "#/">k</a>
      <ul>
        <li class = "B"><a href = "#/">l</a></li>
        <li class = "B"><a href = "#/">m</a></li>
      </ul>
      </li>
    </ul>
</nav>

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 - exploring techniques to alter the relationship between parents and children

I'm facing an issue with transforming the parent-child relationship in my data structure. Currently, it looks like this: { "id": 7, "name": "Folder 1", "parent_folder": null, "folders": ...

Obtaining a background image within a keyframe

I have been experimenting with keyframe animations and am looking to incorporate multiple images into the animation. Specifically, I want to switch out the image every 10% increment to depict someone running. Despite my efforts to use a background-img in ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

I need to style a blockquote so that it floats to the right, but I also want it to be

I want to enhance the appearance of my blockquotes by giving them a different color background and ensuring they stand out from the regular text. Although using float:right helps achieve this effect, I prefer not to force the blockquote to the right side o ...

Email sending through PHP AJAX can be done without refreshing the page. The email action is handled in email.php and incorporated into

I am having trouble sending this with AJAX. The error message I keep getting is: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more assistance, please visit @ jquer ...

Navigating files using NodeJS and ExpressJS

Can NodeJS (or ExpressJS) facilitate the following task? Although I appreciate the flexibility that routing provides, I find the configuration process quite cumbersome. (I don't consider myself an expert in Express) For instance, imagine an applicat ...

Conceal the Angular Bootstrap modal instead of shutting it down

I am utilizing Angular Bootstrap Modal to launch multiple modals, including a video player. http://angular-ui.github.io/bootstrap/#/modal My goal is to maintain the video's current position even when the modal is closed. This way, when I reopen the ...

Struggling with your Dropdown Menu onclick functionality in Javascript? Let me lend

I am seeking assistance with implementing a Javascript onclick Dropdown Menu. The current issue I am facing is that when one menu is opened and another menu is clicked, the previous menu remains open. My desired solution is to have the previously open menu ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Automatically populate a jQuery dropdown box with MySQL data

I have a scenario where I need to create 2 dropdown boxes. The first dropdown box will display all the tables from a database, and when a table is selected, the second dropdown box should be populated with fields from that specific table. Dropdown Box 1: ...

Struggling to effectively transfer a callback function within a series of functions

I am currently utilizing the codebird library to make requests to the Twitter API. The responses from these requests are functioning as expected, but I am looking to pass that response along to my route. Below is a segment of my route.js: router.get(&apos ...

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

What is the best way to perfectly center text within an image, maintaining both vertical and horizontal alignment, all while being contained within an <a> tag?

I've been working with this code snippet. When I set the position of .thumb-title to absolute and use bottom: 50%, it shifts upwards in relation to its own height. .project-thumb { position: relative; } .thumb-title { font: 400 1.5rem 'La ...

Javascript tree structures that enable the drag-and-drop of multiple items

At the moment, our application utilizes the ExtJS tree view. We now have a need for users to be able to select multiple nodes (which the tree view already supports through a pluggable selection model) and then drag these selections to another section of th ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

Dragging objects on a map is done using jQuery and it causes them to bounce

Currently, I am working on implementing the JQuery Draggable feature. My idea is to create a map where I can attach image Divs to it dynamically using Jquery. So far, I have been successful in adding the Divs and making them draggable around the map effici ...

Issue of displaying buttons based on sibling's height under certain conditions

OBJECTIVE I have undertaken a project to enhance my skills in React and TypeScript by developing a UI chat interface. The design requirement is that when a chat message has enough vertical space, its action buttons should appear stacked vertically to the ...