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

Understanding how to break down intricate JSON strings into classes using either VB or C# programming languages

I have a JSON string that needs to be parsed and eventually stored in database tables. My plan is to parse it into VB .NET classes (objects) and then store the data in the tables. I have Newtown imported into my .NET environment, but I'm not very fami ...

Tips for adding a personalized close button to a Bootstrap modal

I need help with a Bootstrap modal in my project that has a close button positioned at the top right corner. I've used CSS to position the button, but it's not staying in one place consistently despite applying absolute positioning. I've tri ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

When I open my website in a new tab using iOS and Chrome, the appearance of the absolute element is being altered

I am experiencing an issue with a div that is positioned absolutely at the bottom left of my website. When I open the site in a new tab using <a target="_blank" href="./index.html">, the bottom value is not being applied correctly ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

Avoid refreshing the page and maintaining the most recent data inputted

On my HTML page, I am trying to implement a button that submits a form using a function. I have set up field validations, and when I click the submit button, it shows an error message but clears out the values I entered and refreshes the form. What I want ...

A vertical divider within an ion-item collection

Currently, I am using Ionic and HTML to implement a vertical line within an ion-item in an ion-list. The desired outcome is to have something similar to this (the colored line after 'all-day'): I attempted the following approach: <ion-list&g ...

Issue with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

Adjusting the Size of Dialog Windows in Lightswitch HTML Client

When using the MS Lightswitch HTML Client, if a dialog menu option contains too many characters to fit within the length of the dialog window, the text will be cut off and replaced with (...). Is there a way to add a scroll bar or adjust the text size in ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...

Pass the form data to a Bootstrap modal upon submission of the form

I'm attempting to retrieve form data and convert it to JSON to display in a modal dialog that opens on the Submit button click! This is my progress so far: HTML <form class="form-horizontal" id="configuration-form"> --irrelevant-- <button ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

Is it possible to submit forms in MIME format?

I've been attempting to send a form via email in MIME format, but I've run into an issue where the input tags are replaced with square brackets. For example: < input type="submit" value="Submit" class="button"/> ==> [Submit] I tried u ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...