Using CSS absolute/relative positioning in a flyout menu: Utilizing specific parent properties (such as left, top, width, vertical/horizontal alignment) while disregarding others

I recently encountered a common issue in CSS involving flyout menus with sub-menus that are shown on hover. When attempting to position the sub-menu directly below the parent list item, I used position:relative; on the parent item and position:absolute;top:0; on the submenu. This approach worked well for vertical alignment.

However, by using position:relative;, I lost the ability to make the submenu 100% width of the page and align it to the very left edge of the page rather than the parent element.

My goal is to maintain vertical alignment with position:relative; on the parent, while inheriting horizontal alignment with position:inherit;.

In the example below, you can see that the submenus are aligned correctly vertically but should start at the very left horizontally:

.clearfix::after {
    content: "";
    clear: both;
    display: table;
}

#my-menu-inner > ul {
  width: 100%;
  background-color: yellow;
  list-style-type: none;
}

#my-menu-inner > ul > li {
  float: left;
  position: relative;
  padding: 20px;
  border: 1px solid black;
  margin: 20px;
}

#my-menu-inner > ul > li > div.sub{
   position: absolute;
   top: 60px;
   background-color: red;
   padding: 40px;
   display: none;
   left: 0;
   width: 100vw;
}

#my-menu-inner > ul > li:hover > div.sub, #my-menu-inner > ul > li:focus > div.sub {
    display: block;
}
<div id="whatever">Just something before ...</div>
<div id="my-menu">
  <div id="my-menu-inner">
    <ul class="clearfix">
      <li>
        <span>foo</span>
        <div class="sub">
          <ul>
            <li>hello</li>
            <li>world</li>
          </ul>
        </div>
      </li>
      <li>
        <span>foo</span>
        <div class="sub">
          <ul>
            <li>please</li>
            <li>alignme</li>
          </ul>
        </div>
      </li>
    </ul>
  </div>
</div>

How can I achieve my desired layout using only pure CSS (answers involving JS will not be accepted)?

Answer №1

Adjust the positioning of the menu item in relation to the ul, not the li:

.clearfix::after {
    content: "";
    clear: both;
    display: table;
}

#my-menu-inner > ul {
  margin:10px;
  width:100%;
  background-color:yellow;
  list-style-type:none;
  position:relative;
}

#my-menu-inner > ul > li {
  float:left;
  padding:20px;
  border:1px solid black;
  margin:20px;
}

#my-menu-inner > ul > li > div.sub {
   position:absolute;
   top:calc(100%  - 20px);
   background-color:red;
   padding:40px;
   display:none;
   left:0;
   width:100vw;
}

#my-menu-inner > ul > li:hover > div.sub, #my-menu-inner > ul > li:focus > div.sub {
    display:block;
}
<div id="whatever">Just something before ...</div>
<div id="my-menu">
  <div id="my-menu-inner">
    <ul class="clearfix">
      <li>
        <span>foo</span>
        <div class="sub">
          <ul>
            <li>hello</li>
            <li>world</li>
          </ul>
        </div>
      </li>
      <li>
        <span>foo</span>
        <div class="sub">
          <ul>
            <li>please</li>
            <li>alignme</li>
          </ul>
        </div>
      </li>
    </ul>
  </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

Switching from Bootstrap's traditional "loading" style progress bar to a more minimal dot style progress bar

Currently, I am implementing a survey progress bar using Bootstrap's "loading" style. Here is the code for the progress bar: <div class="progress" style="height: 20px;"> <div class="progress-bar" role="pro ...

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...

What is the best way to center my image both vertically and horizontally?

Utilizing react.js to develop a template website has been my current project. The issue arose when I began constructing the first component of the site. The dilemma: The picture was not centered on the page, neither vertically nor horizontally. Despite ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

A method to ensure that inline <div> elements occupy the entire available width

The typical solution for this issue is using float, however, it does not work in my situation. I attempted to utilize flexbox and overflow:hidden for the parent element, but unfortunately, it did not resolve the issue. Currently, I am dealing with three i ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

Updating the Wordpress menu: Get rid of the list items and instead add the class ".current-menu-item" directly to the anchor tag

Is there a way to customize the output of wp_nav_menu(); to display a navigation menu like this: <nav> <a>Menu Item</a> <a class="current-menu-item">Menu Item</a> <a>Menu Item</a> <a>Menu Ite ...

Troubleshooting Issue with Angular Property Binding for Image Dimensions

Currently, I am exploring property binding in Angular through an example. The idea is to use an image and bind its width, height, and src attributes using property binding. Surprisingly, even though there are no errors and the image renders successfully vi ...

The hover effect for changing the style of one element when hovering over another element is not functioning as

I've encountered an issue with styling a triangle element using the .something:hover .another{...} selector. Can anyone help me understand what might be causing this problem? .actions { display: flex; margin-top: 20px; max-width: 260px; } .a ...

Creating a custom breakpoint in Bootstrap for adding unique CSS styles

Consider this scenario <div class="col-md-my"> </div> .xx { color: black; } .yy { color: red; } Similar to how Bootstrap adjusts width at different breakpoints. Create a new class called col-md-my When the width exceeds the ...

tips on toggling div visibility based on data filtering

<script> function toggleContent(str) { if(str == 'recent' || str == 'old' && !($(".main_content").is(':visible'))) { $(".main_content").show(); } else if( str == 'newComment') { ...

Dynamic div with height controlled by the content of the background image

I'm trying to figure out how to make a div with a background image of 100% width always maintain the aspect ratio of the image for its height. Is there a way to achieve this? In simpler terms, when I resize the page, I want the div to scale down whil ...

Maintaining consistent div height in Bootstrap 4 flexbox design

I'm currently using Bootstrap 4 with flexbox enabled, but I'm having trouble making the row > col > div boxes have equal heights. I attempted to use position: absolute, but it's not the ideal solution. Below is a screenshot of the is ...

Navigate using React to a different HTML page based on certain conditions

After calling the fetch function, I am able to retrieve the correct token from the backend application. However, every time in this program, even if an incorrect token is retrieved, the program still navigates to StudentLobby (this should only happen when ...

Implementing CSS to achieve striped row styling in a paragraph (not within a table)

Is there a way to achieve alternating row shading within a wrapped paragraph element without using the :nth-child technique? For instance, if we have: <p style="width:100px;"> row 0 -- hello row 1 -- world row 2 -- !!! </p> Some brow ...

Utilize CSS to display line breaks within a browser output

If I wrap text in a <pre> element, line breaks will be displayed in the browser without needing to use <br/> tags. Can this same effect be achieved by utilizing CSS with a <div> element? ...

Uncovering the source of glitchy Angular Animations - could it be caused by CSS, code, or ng-directives? Plus, a bonus XKCD comic for some light-hearted humor

Just finished creating an XKCD app for a MEAN stack class I'm enrolled in, and I'm almost done with it. However, there's this annoying visual bug that's bothering me, especially with the angular animations. Here is the link to my deploy ...

JavaScript code to read a .txt file

Is it possible to use JavaScript to read a text file directly with the file path provided in the code, rather than selecting the file from an open file window? ...

Determine the number of lines in a textarea, taking into account both manual

I have a textarea that I need to validate for input exceeding 6 rows. My JavaScript code works perfectly by checking for scrollbar presence, indicating more than 6 lines of input. However, how can I achieve the same validation using PHP in case JavaScript ...