The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully.

Here is how it looks now

However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don't want it that way.

This is how I want it to be. Please notice the space between the header and the photo (content).

I tried adding padding/margin to the content, but it didn't work. It still scrolls down right to the content, causing it to be covered.

Is there any way I could solve this so there is a noticeable 'space' between the header and the content?

Below is the snippet of my code:

var stickyOffset = $('.nav').offset().top;
    $(window).scroll(function(){
        var sticky = $('.nav'),
            scroll = $(window).scrollTop();
        if (scroll >= stickyOffset) sticky.addClass('nav-fixed');
        else sticky.removeClass('nav-fixed');
});
.top p, .bottom p {
    font-size: 18px;
}
.nav {
    box-shadow: 0 4px 8px 0 rgba(121, 121, 121, 0.1);
    z-index: 99;
    display: table;
    height: 100px;
    width: 100%;
    background-color: #fff672;
}
#home_btn_header {
    margin: 0;
    width: 90px; 
    height: 85px;
    background-image: url(drone.png);
    background-size: cover;
    background-color: transparent;
    border: transparent;
    cursor: pointer;
}
nav {
    display: table-cell;
    vertical-align: middle;
    padding-right: 8%;
}
/* CSS continues... */

It's important to note that the lorem ipsum text lines are being skipped due to the header covering them up.

Answer №1

To achieve the desired white space between the fixed header and content, adjust the styling of the .nav element by setting the background color to white and adding some padding-bottom. Additionally, apply a yellow background color to the nav element with the following CSS changes:

.nav {
  /* other rules... */
  background-color: #FFF;
  padding-bottom: 25px;
}

nav {
  /* other rules... */
  background-color: #fff672;
}

Here is a complete example including the necessary HTML and JavaScript:

var stickyOffset = $('.nav').offset().top;

$(window).scroll(function() {
  var sticky = $('.nav'),
    scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('nav-fixed');
  else sticky.removeClass('nav-fixed');
});
.top p,
.bottom p {
  font-size: 18px;
}

.nav {
  box-shadow: 0 4px 8px 0 rgba(121, 121, 121, 0.1);
  z-index: 99;
  display: table;
  height: 100px;
  width: 100%;
  background-color: #FFF;
  padding-bottom: 25px;
}

#home_btn_header {
  margin: 0;
  width: 90px;
  height: 85px;
  background-image: url(drone.png);
  background-size: cover;
  background-color: transparent;
  border: transparent;
  cursor: pointer;
}

nav {
  display: table-cell;
  vertical-align: middle;
  padding-right: 8%;
  background-color: #fff672;
}

nav ul {
  float: right;
  list-style: none;
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

nav ul::after {
  content: "";
  display: table;
  clear: both;
}

nav ul li {
  font-family: 'Sifonn Pro';
  background-color: transparent;
  border: transparent;
  cursor: pointer;
  text-align: center;
  display: inline;
}

.nav a {
  color: #061127;
  text-decoration: none;
  position: relative;
  font-size: 20px;
  margin: 0 6px;
  padding: 12px 12px;
  display: inline-block;
}

.nav-fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="top">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ...
</div>

It is not recommended to create this white gap as it may cause an awkward visual appearance when scrolling.

Answer №2

To ensure the navigation remains fixed, it is important to maintain the container within the content and only fix the nav position.

var stickyOffset = $('.nav').offset().top;

            $(window).scroll(function(){
            var sticky = $('.nav'),
                scroll = $(window).scrollTop();

            if (scroll >= stickyOffset) sticky.addClass('nav-fixed');
            else sticky.removeClass('nav-fixed');
            });
.top p, .bottom p {
font-size: 18px;
}


.nav {
                box-shadow: 0 4px 8px 0 rgba(121, 121, 121, 0.1);
                z-index: 99;
                height: 100px;
                width: 100%;
                background-color: #fff672;
            }
            #home_btn_header {
                margin: 0;
                width: 90px; height: 85px;
                background-image: url(drone.png);
                background-size: cover;
                background-color: transparent;
                border: transparent;
                cursor: pointer;
            }
            nav {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                padding-right: 8%;
            }
            nav ul {
                float: right;
                list-style: none;
                list-style-type: none;
                margin: 0;
                padding: 0;
                overflow: hidden;
            }
            nav ul::after {
                content: "";
                display: table;
                clear: both;
            }
            nav ul li {
                font-family: 'Sifonn Pro';
                background-color: transparent;
                border: transparent;
                cursor: pointer;
                text-align: center;
                display: inline;
            }
            .nav a {
                color: #061127;
                text-decoration: none;
                position: relative;
                font-size: 20px;
                margin: 0 6px;
                padding: 12px 12px;
                display: inline-block;
            }
            .nav-fixed {
                position: fixed;
                top: 0; left: 0;
                width: 100%;
            }
            .nav-container {
              height: 100px
            }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="top">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  <p>Lorem ipsum dolor...

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

Efficient methods to reach the desired result using Selenium WebDriver promises

After working on a piece of code that utilizes Selenium WebDriver to retrieve the text of an element, I am wondering if there is a more concise way to accomplish this task? async function getText(driver, locator) { return await (await driver.findEleme ...

Can you explain the functionality of the following Express router?

In the tutorial I am currently following, there are 2 router methods used to retrieve articles from the database. router.param('article', function(req, res, next, slug) { Article.findOne({ slug: slug}) .populate('author') .th ...

Creating a CSS rollover effect for your logo on a WordPress website

Struggling to implement a CSS image rollover on a Wordpress header logo. The solution may be simple for you experts, but I can't find it anywhere on Stackoverflow. Could it have something to do with the position? Adding :relative or :absolute doesn&ap ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Reordering Divs in Bootstrap 3 Specifically for Small Screens

Just getting started with my first responsive design project, and I'm wondering if it's possible to achieve something like this using Bootstrap 3. The goal is to switch from the current layout: https://i.stack.imgur.com/lABXp.jpg To https://i. ...

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...

Exploring CSS3 Border-Radius Compatibility with Internet Explorer 9

After creating a CSS3 gradient using ColorZilla, I noticed an issue with the DATA URI that seems to be causing problems. Check out my fiddle link here: http://jsfiddle.net/cY7Lp/. In WebKit & Firefox browsers, the rounded corners display correctly. Ho ...

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

html table displaying incorrect data while using dynamic data in vue 3

example status 1 Hello there! I'm trying to create a table (check out example status 1 for guidance). Here's the code snippet I am using: <table> <tr> <th>Product</th> <th>Price</th> <th>Av ...

Unveiling the Magic: Enhancing Raphaeljs with Interactive Click Events on a Delicious Slice of the

I'm having trouble responding to a click event on each slice of a Raphael Pie Chart. I've tried implementing the code below, but it doesn't seem to be working. The code is just two lines, commented as "My Code", in the example from the offic ...

Obtain the URL currently loaded in the browser, excluding any URLs retrieved using jQuery's $.get function

I am working with a controller named examples.php, which contains the following function: public function total_records_of_current_dataset(){ $url = base_url().uri_string(); $get_current_segment = $this->uri->segment(3); $count_all_rows ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

How can we prevent the navigation from fading out when scrolling back up, as JQuery control the opacity of the Nav to fade in?

Looking for some guidance on jQuery assistance. I currently have a fixed navigation bar at the top of my webpage with an initial opacity set to 0 upon page load. As the user scrolls down, I want the navigation bar to fade in using the following code: fun ...

Easily transfer a Jquery array to a Rails controller action!

I'm struggling to understand how to send a query in JSON format to a Rails controller#action. Here's what I have: var myarray = []; ( with values ) This is the controller action I want to post to: def process end I've searched everywher ...

Problem with Labels Overlapping and Blocking Text Fields

My issue is that when I interact with the text field, the label "Type your New Task here" moves up and gets covered by what looks like a white overlay. How can I fix this so that the label stays visible at all times? Prior to engagement: https://i.stack.i ...