"Enhance Your Website with a Sticky Bootstrap Navbar and Seamless Scroll Design - Elevating Padding and Margin-

I am currently working on incorporating a bootstrap sticky navbar with a fixed height of 81px and smooth-scroll behavior into my project.

The website's HTML structure includes section tags like

<section class="section" id="news">
, which allows users to navigate to specific sections by clicking on
<a class="nav-link" href="#news">News</a>
in the navbar. To achieve this, I am utilizing CSS and JS technologies that are loaded at the beginning of the <body>:

Initially, everything works perfectly: when the browser window reaches the bootstrap specific --breakpoint-lg of 992px, the navbar collapses into a burger menu. To accommodate the fixed-height navbar, I have added code to my custom.css (loaded after the bootstrap.min.css), following a helpful tip from https://css-tricks.com/fixed-headers-on-page-links-and-overlapping-content-oh-my/

@media (max-width: 991px) {
    section {
        padding-top: 382px;
        margin-top: -382px;
    }
}

@media (min-width: 992px) {
    section {
        padding-top: 80px;
        margin-top: -80px;
    }
}

While this setup functions properly on larger browser window sizes, when loaded on smaller widths (991px and below) - particularly on mobile devices - clicking on the navbar-link causes a slight vertical offset. Do you have any insights into why this occurs? It appears that my media query for max-width: 991px may not be working as intended.

Answer №1

I truly appreciate the tip on incorporating a snippet. It really demonstrates an effective technique using background colors to differentiate the divs within the sections. This ensures that the crucial h2-heading stands out at the beginning of each area that we navigate to. Omitting the background colors would still maintain a seamless experience for the audience, especially when reading continuous text with h2 headers interspersed throughout.

After some trial and error, I believe I have arrived at a satisfactory solution. The issue I encountered with the padding-top / margin-top approach stemmed from inadvertently styling the <section> instead of the intended

<div class="container" id="first">
in the CSS. As a result, the @media query became unnecessary eventually.

$(function() {
  $(".nav-link").click(function() {
    let nav = $(".navbar-collapse");
    if (nav.hasClass("show")) {
      nav.removeClass("show");
    }
  })
})
html {
  --scroll-behavior: smooth;
  scroll-behavior: smooth;
  font-family: 'scroll-behavior: smooth;', sans-serif;
}

.container {
  padding-top: 80px;
  margin-top: -80px;
}

p {
  line-height: 2em;
}

.navbar {
  background: lightgoldenrodyellow;
}

.container {
  display: grid;
}

#first {
  background-color: lightcoral;
}

#second {
  background-color: lightgreen;
}

#third {
  background-color: lightblue;
}

#fourth {
  background-color: lightgray;
}

#fifth {
  background-color: lightyellow;
}
<!DOCTYPE html>
<html lang="zxx">

<head>
  <title>bootstrap / breakpoint / smooth-scroll issue</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71131e1e05020503100131455f475f41">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="custom.css">
</head>

<body>

  <!-- JS -->
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c766d69796e655c2f322a322c">[email protected]</a>/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63010c0c17101711021323574d554d53">[email protected]</a>/dist/js/bootstrap.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d574c48584f4413585c4e54553a475e5850314d40490e514c464e">[email protected]</a>/jquery.easing.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c1dfddddc6dac1d1c0dddedef2829c869c82">[email protected]</a>/smoothscroll.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b3adafafb4a8b3a3b2afacaceda1aea3a8afb2edb0afacb9a6a9acac80f1eef3eef4">[email protected]</a>/dist/index.min.js"></script>
  <script src="script.js"></script>

  <!-- Navigation Start -->
  <nav class="navbar navbar-expand-lg sticky-top">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <i class="fas fa-bars"></i>
            </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto navbar-center">
        <li class="nav-item active">
          <a class="nav-link" href="#first">First</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#second">Second</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#third">Third</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#fourth">Fourth</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#fifth">Fifth</a>
        </li>
      </ul>
    </div>
  </nav>
  <!-- Navigation End -->

  <!-- Content Start -->
  <section class="section">
    <div class="container" id="first">
      <h3>first</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing 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. ... (Content truncated for brevity)

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

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Position the image at the center above the text

I am trying to position multiple images side by side, with each image having a date displayed beneath it. The challenge I am facing is that the length of the date extends beyond the width of the image, and I would like to center the image on top of its c ...

Incorporate fresh data into dropdown options upon selection using Vue3

Can anyone assist me with populating specific input fields on a form using Vue 3? Currently, when a user selects an option from my dropdown menu, all inputs are displayed instead of just the relevant ones. Below is the select dropdown code: <select v- ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

Show a specific item when selecting an option from a dropdown menu

Hey there, I have a question regarding creating a theme for the Genesis Framework. Right now, I'm facing a challenge with one particular element. Here's the situation: I've got two drop-down lists, but I only want the second one to be visib ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

Encountering a maximum call stack size error is a common issue when implementing d3.layout.partition in Angular

I recently developed an AngularJS directive to generate a D3 sunburst chart, but I'm encountering issues. I'm receiving a maximum call stack error in Chrome and a too much recursion error in Firefox. After some investigation, I found that the pro ...

Transitions in Vue do not function properly when used in conjunction with a router-view containing a

Recently, I developed a component where I implemented router-view exclusively to facilitate route-based changes. It's worth mentioning that this is the second instance of router-view, with the first one residing in the App.vue component. Interestingly ...

Issue with React Redux: Passing down a component's method to its children results in an undefined error

Currently, I am working on creating a todo list using React and Redux. In my code snippet provided below, there is a component that includes a function called onDeleteItem. The issue I am facing is the inability to pass the onDeleteItem function to the s ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

Tips for updating the value of the most recently created div in an ng-repeat loop

Within my HTML document, the following code is present: <div ng-repeat="selection in selections" style="margin-left:{{marginLeft}}%;width:{{progress}}%;background-color:{{selection}}"> </div> In my controller, I have implemented function ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Update a particular class following an AJAX POST request in JavaScript

After conducting extensive research, I have come here seeking your assistance with a particular issue: I am using a comment system with multiple forms on the same page (utilizing FOSCommentBundle in Symfony). My goal is to be able to post comments via Aja ...

Is it possible to dictate a custom sequence of operations in THREE.js?

Check out this question on Stack Overflow regarding Threejs Transform Matrix ordering: Threejs Transform Matrix ordering I'm currently working on depicting the orbits of planets and I've encountered some difficulties when trying to change the in ...

The jQuery fadeToggle function toggles the visibility of an element starting from hidden instead

I'm having an issue where text in my div only appears on the second click, instead of the first. What could be causing this problem? $('#fPaperCirclePic').on('click', function () { $('#fPaperCircleText, #isargebla, #moq10 ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...