Positioning an immovable element beneath a fixed element that can vary in height

I am working on a webpage that features a fixed menu at the top-left corner, followed by the main content. My goal is to ensure that the content appears below the menu, but since I do not know the exact height of the menu in advance (as it can vary based on the user's device or window size), setting a fixed top margin for the content is not feasible. As a result, when the page loads, the menu appears at the top and the content follows below it, with the ability to scroll the content behind the fixed menu.

While one workaround involves duplicating the menu above the content as a static hidden element, I am seeking a more elegant solution.

I envision something like this:

<div id="menu">
    Vertical list items go here
</div>
<div id="content">
    Main content goes here
</div>


#menu {
    position: fixed;
    z-index: 999;
}

#content { margin-top: [height of #menu, which is unknown until the page renders] }

Answer №1

If you're looking to make your menu dynamic, a simple JavaScript solution can help. By setting the position and margin top on window load, you can ensure that the menu stays in place and resolves any potential issues.

#menu {z-index: 999; }

<div id="menu">
  a (vertical) list goes here
</div>
<div id="content">
   the content goes here
</div>
<script>
  window.onload = function() {
    var menuElement = document.getElementById("menu");
    var menuHeight = menuElement.offsetHeight;
    menuElement.style.position = "fixed";
    document.getElementById("content").style.marginTop = menuHeight+"px";
  };
</script>

Answer №2

To achieve this effect, you will need to utilize JavaScript. When the user starts scrolling, add the class scrolled and set its position to fixed.

var scrollPosition = "";

$(window).scroll(function () {

  scrollPosition = $(window).scrollTop();

  scrollPosition > 50 ? $('#menu').addClass("scrolled") : $('#menu').removeClass("scrolled");
});
body {
margin:0;
padding:0;
}
#menu {
border: 1px solid red;
}

#menu.scrolled {
position: fixed;
top:0;
left:0;
right:0;
background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
    a (vertical) list goes here
</div>
<div id="content">
    Insert your content here...
</div>

Alternative CSS Approach:

.wrapper {
padding-top: 20px; /* adjust padding top based on menu height */
}

#menu {
position: fixed;
top:0;
left:0;
right:0;
border: 1px solid red;
background-color: #fff;
}
<div class="wrapper">
<div id="menu">
    Your vertical list goes here
</div>
<div id="content">
    Insert your content here...
</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

Enable scrolling exclusively for the content within a tab, without affecting the tab label in Clarity Tabs

I have a tab with lengthy content in my project (check out the StackBlitz reference here). This causes the appearance of a scroll. The corresponding code snippet is provided below: <div class="content-container"> <div class=&qu ...

What is preventing me from concealing my input field when its type is set to "file"?

I've been attempting to conceal my input field of a file type, but even with the hidden attribute, it refuses to hide. Interestingly, once I remove type="file", the code successfully hides itself Does anyone have insight on how I can hide ...

Showing the json encoded array received from an ajax response

I have encountered this data result {"policy":[{"id":"1","policy_name":"Policy 1","description":"Testing","status":"Active","valid_until":"2022-05-18& ...

Markdown boasts of a sturdy partially-horizontal line

Is there a way to create a partially colored line in Markdown? I attempted using the following code: <hr style="border:0.3px solid green; width:40%"> </hr> However, instead of a partial green line, I am seeing a full gray line. Any idea on w ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...

Display additional content button, dynamic div identification

I've created a small script that includes a "show more" button at the end of displaying 10 entries. Here is the code: <div id="more<?=$lastid;?>"> <a onclick="showmore(<?=$lastid;?>);">More</a> </div> And here ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

Stay up-to-date with the latest headlines on your Android device!

I am currently developing an Android application and I need to retrieve the most recent news from this specific page, specifically the tab labeled "NYHEDER": Once I have retrieved the news, I plan to display it on the app's screen. I have come acros ...

Guide to changing an image on a canvas with KineticJS

I am currently working on developing a canvas that will display a hotel floor view. I have images stored in a database which I am drawing onto the canvas using x and y coordinates from the database as reference points. However, I want to add touch events t ...

Creating the main webpage's HTML through the Codebehind feature in ASP.Net using VB

Currently, I am immersed in a recreational project aimed at enhancing my understanding of vb.net and its interconnectivity. I welcome any suggestions that could potentially enhance the efficiency of my approach! My present focus involves extracting data f ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Targeting an HTML form to the top frame

Currently, I have a homepage set up with two frames. (Yes, I am aware it's a frame and not an iFrame, but unfortunately, I cannot make any changes to it at this point, so I am in need of a solution for my question.) <frameset rows="130pt,*" frameb ...

Creating trails by following the cursor's movement in KineticJS

Currently, I am working on a drawing application using KineticJS. While I have successfully used it to draw shapes and straight lines by following the method outlined in KineticJS - Drawing Lines with Mouse, I now need to draw a line along the mouse's ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

Using Bootstrap 4: How to maximize the width of a span element placed near a label

I need to adjust the width of a span next to its label in my project. My goal is to show multiple groups {label / data} on the same line. To achieve this, I divided the row into 4 columns and tried to set a specific width for a span. However, no matter wh ...

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...

The embed video is camouflaged within the bootstrap mobile display

I am currently using the latest version of bootstrap and bootswatch united theme to build and explore a standard website. The website is live at this link live site, featuring an embedded section on the right side as shown. My choice for the view engine is ...

Tips for switching "a" tag elements to reveal concealed DIVs in a similar way to the Facebook notification center

I have a situation in my code where I need to toggle between two a elements to display a hidden div with content one at a time. This functionality is similar to how the Facebook notification center works when you click on the icons, which I'm sure mos ...

What is the reason for the overflow occurring in a container of identical size due to this particular element?

I've encountered an issue while trying to create a div with a scrollbar that only appears when the elements within it don't fit the default area. <div style="overflow-y: auto; height: 36px;"> <img src="." width="36" height="36" /> ...

What might be causing the background color to remain the same when focusing on a div element

I am trying to change the background color of a parent div when an input field within it is in focus using CSS only. However, my current code does not seem to be working as expected. This is what I have tried: .a:focus{ background-color:red; border:2 ...