Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping.

I tried solving it with margins and paddings but believe there must be a simpler solution out there. Check out my attempt here

I spent hours experimenting but couldn't find an ideal fix, something always seemed off or didn't work as intended.

$(function() {
  var shrinkHeader = 100;
  $(window).scroll(function() {
    var scroll = getCurrentScroll();
    if (scroll >= shrinkHeader) {
      $('#navbar').addClass('shrink');
    } else {
      $('#navbar').removeClass('shrink');
    }
  });

  function getCurrentScroll() {
    return window.pageYOffset || document.documentElement.scrollTop;
  }
});
// JavaScript Document

$(document).ready(function() {

  var navTop = $('#navbar').offset().top;
  var navHeight = $('#navbar').height();
  var windowH = $(window).height();

  $('.section').height(windowH);

  $(document).scroll(function() {
    var st = $(this).scrollTop();

    //for the nav bar:
    if (st > navTop) {
      $('#navbar').addClass('fix');
      $('.section:eq(0)').css({
        'margin-top': navHeight
      }); //fix  scrolling issue due to the fix nav bar
    } else {
      $('#navbar').removeClass('fix');
      $('.section:eq(0)').css({
        'margin-top': '0'
      });
    }

    $('.section').each(function(index, element) {
      if (st + navHeight > $(this).offset().top && st + navHeight <= $(this).offset().top + $(this).height()) {
        $(this).addClass('active');

        var id = $(this).attr('id');
        $('a[href="#' + id + '"]').parent('li').addClass('active');
        // or $('#nav li:eq('+index+')').addClass('active');
      } else {
        $(this).removeClass('active');

        var id = $(this).attr('id');
        $('a[href="#' + id + '"]').parent('li').removeClass('active');
        //or $('#nav li:eq('+index+')').removeClass('active');
      }

    });
  });

});

//
/* MAIN */

/* SECTION HOME */
#home {
  height: 853px !important;
  display: flex;
  z-index: -1;
  position: relative;
  top: -128px;
  padding-top: 128px;
}

#homebild {
  width: 1280px;
  height: 853px;
}

/* SECTION WIR-UEBER-UNS */
#wir-ueber-uns {
  height: 853px !important;
  display: flex;
  top: -208px;
  padding-top: 80px;
  z-index: -2;
  position: relative;
  background-color: lightblue;
}

#wir-ueber-unsbild {
  width: 1280px;
  height: 853px;
}

/* SECTION AKTIONEN */
#aktionen {
  height: 853px !important;
  display: flex;
  padding-top: 80px;
  top: -288px;
  z-index: -3;
  position: relative;
  background-color: darkblue;
}

#aktionenbild {
  width: 1280px;
  height: 853px;
}

/* SECTION TERMINVEREINBARUNG */
#terminvereinbarung {
  height: 853px !important;
  padding-top: 80px;
  top: -368px;
  display: flex;
  z-index: -4;
  position: relative;
  background-color: red;
}

#terminvereinbarungbild {
  width: 1280px;
  height: 853px;
}

/* SECTION INFOS */
#infos {
  height: 772px !important;
  width: 1280px;
  display: flex;
  padding-top: 80px;
  top: -448px;
  z-index: -5;
  position: relative;
  background-color: darkblue;
}

/* MAIN ENDE */
<!DOCTYPE html>
<html>

  <head>
    <title>OptikTack</title>
    <link href="style.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
  </head>

  <body>
    <div id="container">
      <div class="body">
        <!-- NAVIGATION -->
        <nav id="navbar">
          <script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
          <script src="javascript/navbar fixed.js"></script>
          <a href="#home" id="logo"><img src="https://i.postimg.cc/przxCGcx/Logo.png" class="logo"></a>
          <ul>
            <li class="hvr-sweep-to-top active"><a href="#home">Home</a></li>
            <li class="hvr-sweep-to-top"><a href="#wir-ueber-uns">Wir über uns</a></li>
            <li class="hvr-sweep-to-top"><a href="#aktionen">Aktionen</a></li>
            <li class="hvr-sweep-to-top"><a href="#terminvereinbarung">Terminvereinbarung</a></li>
            <li class="hvr-sweep-to-top"><a href="#infos">Infos</a></li>
          </ul>
        </nav>
        <!-- NAVIGATION ENDE -->
        <!-- MAIN -->
        <div id="spacer"></div>
        <!-- home section -->
        <section id="home" class="section">
          <div>
            <img src="https://i.postimg.cc/tgk5cWmx/Bild-1.jpg" alt="Frau" id="homebild" width="1280px">
          </div>
        </section>
        <!-- home section ende -->
        <!-- wir-ueber-uns section -->
        <section id="wir-ueber-uns" class="section">
          <div>
            <img src="https://i.postimg.cc/FH6RSxbF/Bild-2.jpg" width="1280px" id="wir-ueber-unsbild">
          </div>
        </section>
        <!-- wir-ueber-uns section ende -->
        <!-- aktionen section -->
        <div id="reference"></div>
        <section id="aktionen" class="section">
          <div>
            <img src="https://i.postimg.cc/k5P0L6qF/Bild-5.jpg" width="1280px" id="aktionenbild">
          </div>
        </section>
        <!-- aktionen section ende -->
        <!-- terminvereinbarung section -->
        <section id="terminvereinbarung" class="section">
          <div>
            <img src="https://i.postimg.cc/6q8b8tBp/Bild-9.jpg" width="1280px" id="terminverinbarungbild">
          </div>
        </section>
        <!-- terminvereinbarung section ende -->
        <!-- infos section -->
        <section id="infos" class="section">
          <div>
            <p>section 5</p>
          </div>
        </section>
        <!-- infos section ende -->
        <!-- MAIN ENDE -->

Answer №1

To enhance the appearance of all anchor tags, you can apply a class that includes a pseudo-element with specific attributes:

.your_anchor_class::before { 
  display: block; 
  content: " "; 
  margin-top: -80px; 
  height: 80px; 
  visibility: hidden; 
  pointer-events: none;
}

Adjust the values such as 80px and -80px according to the height of your fixed header. This will create pseudo elements that match the height of the header and appear behind it, aligning with the main elements below the header.

UPDATE after reviewing your Fiddle:

It appears that the scrolling behavior is animated rather than direct jumping to anchors. Therefore, some modifications need to be made in the scrolling script to accommodate this behavior.

A small adjustment is made in the Javascript code (at the end of the HTML code): I included " - 80 " in the animate function to offset the scroll animation by 80px. Please note that no offset is added if the anchor link is #home, as the page should scroll to the top without any offset:

<!-- Smooth Scroll -->
<script>
  $('a').click(function() {
  var scrollziel = $(this).attr('href');
    if(scrollziel == '#home') {
      $('html, body').animate({
        scrollTop: 0
      }, 500);
      return false;
    } else {
      $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 80
      }, 500);
      return false;
    }
  });
</script>
<!-- Smooth Scroll End -->

This adjustment resolves the issue. You can view the updated version of your fiddle with this modification only: https://jsfiddle.net/c1gjybtf/

Answer №2

After some adjustments,

  font-family: 'Saira', 'Roboto', Segoe UI, Helvetica Neue, Arial, sans-serif;
  box-sizing: border-box;
}

I also modified the top: to -80px for each section (as my navbar is 80px tall)

This resulted in a cleaner look

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

Executing a file upload using ng-click="upload('files')" within Selenium Webdriver

Is it possible to automate a file upload when the HTML code does not include an < input type='file' > instead, uses a link <a ng-click="upload('files')"> File Upload </a> Clicking this link opens a file selector f ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

Tips on invoking a Stencil component function or method from beyond the Vue instance

Is it possible to trigger a function in a Stencil component from the parent Vue instance? For example, I would like to call the callChild() method in the Vue instance, which will then trigger the doSomething() function in the Stencil component. The main ...

String containing the character '+' was received when performing an Ajax post and appending the string to FormData in c#

I recently set up a page for saving text and images to a database. To achieve this, I employed form-data. However, I encountered an issue where spaces in the text were being replaced by '+' symbols. Below is the code snippet of what I attempted: ...

Opacity problem when hovering on Chrome

Work in progress: Hello everyone, I'm facing an issue with a hover effect that only seems to be occurring in Chrome. When hovering over a tile, the background color changes, the image opacity decreases, and an icon appears over the image. In Chro ...

Issue with inconsistent error handling in Mui DateTimePicker and react-hook-form

I am currently facing an issue with a DateTimePicker component that I am trying to integrate into a form controlled by react-hook-form. The validation is straightforward - I am using the disablePast prop on the DateTimePicker to ensure that the selected da ...

Create a CSS border that resembles the one used in Google's signup form

lies a curious inquiry: what unique border style is in play here? It rests slightly raised against the backdrop, creating an intriguing visual effect. After combing through various sources online, the answer still eludes me. Perhaps turning to Google' ...

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". https://i.sstatic.net/galzh.png Upon clicking on the link referring to "exte ...

Uncover comprehensive error analysis via AJAX communication

I am seeking a more comprehensive response regarding a domain through the use of ajax. Currently, I possess the following code: $.ajax({ url: domain, type: "POST", data: { //To identify any errors, an empty response is set xml ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...

Maintain the state of the toggle div after page refresh or modification

In this scenario, I am looking to ensure that my div remains open even if the page is changed or refreshed. Below is the HTML and JavaScript code provided: You can view the working code here: http://jsfiddle.net/wasimkazi/fauNg/1/ $(".widget2").hide( ...

Retrieve the heading from a pop-up box

This jQuery tooltip allows for popups from another HTML page to be created. UPDATE: I have provided an example HERE The issue arises when trying to retrieve the title from the popup. Currently, using document.title displays the title of the current page ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

Adjust the position of the div so that it remains visible as you scroll

Is it possible to position an element within a container that contains a wide table with overflow property so that the element remains visible while scrolling horizontally through the table data? <div id = "mainContainer" style = "width:300px; overflow ...

The Challenge of Logging in with the Loopback Angular SDK

I have set up a "user" named model with the base class of "User". I'm attempting to log in a user on my Angular App using the service generated by lb-ng, but it doesn't seem to be working. When I call User.login() in my Login controller, providin ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

Tips for avoiding duplicate usernames in mySQL when working with PHP

My users register for the database, but how can I prevent duplicate usernames in the database? I want to inform the user if their username already exists. <?php $error = ""; // error $GoodJob = ""; if(isset($_POST[&apos ...