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

A guide on converting JSON strings into arrays using Javascript

In my JavaScript program, I have a Mocha test that checks if all available currencies are displayed in a drop-down list: it('displays all available currencies in drop down list', () => { return invoiceEditPage.details.currencyDropDown.dr ...

Setting line height as a pixel value does not yield the desired result

$(element).css(options.css).attr(options.attr).addClass(options.class) //ensure line-height is correctly assigned if($(element).is('p') && _.isString(options.css['line-height'])){ console.log('line-height assigned: &apos ...

Locate the closest text to an element within an HTML document

My HTML content contains specific tags with text and images. If I am able to select an image, is there a way to retrieve the text nearest to that image? <div class="topStory"> <div class="photo"> <a href="somelink"><img src="s ...

Utilizing REST API calls for querying data in MongoDB

My goal is to send an XMLHttpRequest to mongoDB using AJAX to retrieve a document. This is the code I have written: function getJsonDocumentByModeldid(model_id) { var inputVal = document.getElementById('inputModelId').value; alert(input ...

Having trouble accessing the templateUrl for HTML in Angular version 1.6

I am currently working on a basic Angular 1.6 web application. Although I have created a state for the URL "/", it seems that Angular is unable to locate the file for some reason. The folder structure looks like this: https://i.stack.imgur.com/2p6bP.png ...

Display the PHP variable's contents as a text string within an HTML document

Looking at a WordPress PHP script, I came across the following snippet: echo '<div class="slide-media">' . $slide_media . '</div><!--/.slide-media-->' . "\n"; } I am interested in viewing the ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

An element failing to submit using AJAX requests

I have a login form with an <a> element that I want to use for making a post request. However, when I'm examining the backend Django code during debugging, it seems to interpret the request method as GET instead of POST. HTML <form id= ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

Is there a way to execute a Python script when submitting an HTML form?

I have created an HTML form and my goal is to utilize Python to transfer the data from this form into an SQLite database file. Currently, I am attempting to achieve this using CGI. I don't require anything extravagant. Below is the code that I am work ...

Incorporate an icon into a text input field using Material UI and React

I have a form with a text input element: <FormControl className='searchOrder'> <input className='form-control' type='text' placeholder='Search order' aria-label='Search&ap ...

Responsive design with Semantic UI

Can you please provide an example of how to design for different screen sizes using Semantic UI instead of Bootstrap? I'm looking for something similar to Bootstrap's sm and lg classes. For instance, would it look like this: <div class="col s ...

Integrate ThreeJs models into an Angular JS application

I have a question that pertains to my webapp development. I am currently utilizing Angular Js (v1.5/1.6) and I would like to incorporate some minimalistic 3D animated models by integrating Three Js. Although I have attempted to configure certain aspects, ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Transforming the DOM using jQuery

I am looking to manipulate the DOM using jQuery. This is the initial source code: <td class="name"><a href="position_details.php?x=-109&amp;y=95">21</a> </td> <td class="name"><a href="position_details.php?x=-109& ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

Improved Approach for Replacing if/else Statements

I'm looking to streamline the controller used in my SQL command for filtering records based on specific criteria. The current approach below is functional, but not without its limitations. One major issue is scalability - adding more criteria in the f ...

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

Editing an XML file on the browser and saving it in its original location on the local file system

Seeking assistance with editing an XML file directly from the browser on a local file system and saving it back to its original location. I have conducted extensive research using Google, but have not been able to find a suitable solution. Any help or gu ...