Ensure that the navbar remains within the container as you scroll down the page

With the implementation of bootstrap 4, I have successfully integrated a fixed navbar inside a container. Initially, at the top of the page, it occupies the full width, but as soon as I start scrolling, it smoothly transitions into the confines of the container.

Is there a way to ensure that when I scroll back to the very top, the navbar returns to its original position within the container?

I've also included a feature where the navbar changes color and background color when scrolled, highlighting the active section on the page.

<body data-spy="scroll" data-target="#navbarScroll">
<!-- Navigation Section -->
<div id="navbarScroll">
  <nav class="navbar container fixed-top navbar-expand-lg navbar-light">
    <a class="navbar-brand" href="#"></a><!-- removed brand name leaving only toggler -->
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navi" aria-controls="navi" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-end" id="navi">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#about">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#portfolio">Portfolio</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#contact">Contact</a>
        </li>
      <ul>
    </div>
  </nav>
</div>

<!-- About Section -->
<div class="backgroundColor">
  <div class="anchor" id="about"></div>
  <div class="container">
    <div class="row one">
      <div class="col-md-12">
        <img src="http://res.cloudinary.com/lyoon/image/upload/c_scale,h_350,w_350/v1503457656/02_27_16_2_u3qrdf.jpg" class="img-fluid profpic" alt="Caught a bass!">
      </div>
      <div class="description col-md-8">
        <p>Front-End Developer and UX/UI Designer, with experience in HTML, CSS, and JavaScript. Proficient in Bootstrap for CSS, jQuery for JavaScript, and responsive web design.</p><hr>
        <p>Passionate junior Web Developer who enjoys programming, music, and nature walks.</p>
      </div>
    </div>

    <!-- Portfolio Section -->
    <div class="anchor" id="portfolio"></div>
    <div class="row two">
      <div class="col-md-12">
        <h3 class="titleport">Portfolio</h3>
      </div>
      <div class="col-md-12">
        <p class="secondPara">Click on the image to view demo. Click the app title below the image to view the code.
          <br />
          All projects are created using HTML, CSS, and JavaScript.
        </p>
      </div>
    </div>
    <div class="row three">
      <div class="col-md-6 img-section1">
        <figure>
          <a href="https://lawrenceyoon.github.io/Score_Keeper/">
            <img src="http://res.cloudinary.com/lyoon/image/upload/c_scale,h_400,w_500/v1509214906/Screen_Shot_2017-10-28_at_11.21.21_AM_w2ieuq.png" class="img-fluid" alt="Score Keeper Game">
          </a>
          <figcaption><a href="https://github.com/lawrenceyoon/Score_Keeper">Score Keeper</a></figcaption>
        </figure>
      </div>>
    
      // Rest of the portfolio entries shortened for conciseness
    
    </div>

    <!-- Contact Section -->
    <div class="anchor" id="contact"></div>
    <div class="row four">
      <div class="col-md-12">
        <h3 class="titlecontact">Contact</h3>
      </div>
      <div class="col-md-12">
        <p class="contactme">Feel free to reach out via email if you wish to get in touch!</p>
      </div>
    </div>
  </div><!-- End of Container -->
</div><!-- End Background Color -->

Below is the defined CSS style section...

/* General Styling */
body {
  position: relative;
  font-family: 'Slabo', serif;
  font-size: 20px;
  letter-spacing: 0.5px;
}

h3 {
  font-family: 'Oswald', sans-serif;
  font-size: 40px;
  letter-spacing: 2px;
}

.container {
  background-color: rgb(255, 255, 255);
}

.backgroundColor {
  background-color: rgb(163, 167, 168);
}

.anchor {
  position: relative;
  top: -46px; /* Added for spacing after clicking on nav links so navbar doesn't overlap */
}

/* Navbar Styling */
.navbar {
  background-color: white;
  padding: 0;
}

// Active Link Styling
.navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav 
.nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-
light .navbar-nav .show>.nav-link {
background-color: rgb(163, 167, 168);
  color: white;
}

/* About Section Styling */
.one {
  text-align: center;
  border-bottom: 1px solid gray;
  margin-top: 46px; /* Necessary for preventing navbar from overlapping profile picture MUST MATCH .ANCHOR */
}

.profpic {
  border-radius: 50%;
  margin-top: 30px;
  margin: 30px auto 0px auto;
}

.description {
  margin: 30px auto;
}

/* Portfolio Section Styling */
.two {
  text-align: center;
}

.titleport {
  padding: 30px 0px;
  margin: 0px;
}

p.secondPara {
  margin-bottom: 30px;
}

.three {
  border-bottom: 1px solid gray;
  padding-bottom: 25px;
}

.img-section1, .img-section2, .img-section3, .img-section4 {
  text-align: center;
}

img {
  border-radius: 5%;
}

figure {
  margin: 0px;
}

figcaption {
  margin: 5px 0px;
}

/* Contact Section Styling */
.titlecontact {
  padding: 30px 0px;
  text-align: center;
  margin: 0px;
}

.contactme {
  text-align: center;
  font-style: italic;
  margin: 0px;
}

a {
  color: inherit;
  transition: all 0.5s;
  -webkit-transition: all.5s;
  -moz-transition: all 0.5s;
}

a:hover {
  color: rgb(1, 193, 213);
  text-decoration: none;
}

.iconContainer {
  text-align: center;
  margin: 30px 0;
}

a.icons {
  text-decoration: none;
  margin: 10px;
}

Answer №1

Solution:

Make the switch from margin-top to padding-top.

Explanation:

Padding represents the space between an element's content and its border, while margin signifies the area outside the border. The use of margin was causing the entire div to shift downwards, revealing the white background color of the body, creating a visual illusion. To resolve this, you can adjust the body background to match the grey background color instead.

.one {
    text-align: center;
    border-bottom: 1px solid gray;
    padding-top: 46px; /* included here to avoid overlap with navbar 
    image MUST MATCH .ANCHOR */
}

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

Show the list in a circular buffer fashion

I am working on a project that involves creating a unique UI element. In Frame #2 of my professionally designed diagram, I envision a list that functions as a ring buffer/rolodex when it exceeds four items. The list would scroll in a loop with the top and ...

Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code. <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); /* ...

An undefined PHP index error was encountered by Ajax, while the other one did not face the same issue

I encountered an issue with ajax where I am receiving an undefined index error on my variables when making a call. Strangely, I have other ajax calls functioning perfectly fine across my website except for this particular one which is giving me troubles. I ...

Sticky positioning for dropdown menu in table column body

Greetings, I need some assistance with a formatting issue. My goal is to make the first and second columns of my table sticky by applying a "sticky" position to them. However, one of the columns contains a dropdown menu and the problem is that the content ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

CSS-Only tooltip that adjusts size dynamically

Having trouble getting a tooltip to work exactly as desired? I need to implement tooltips for the contents of dynamically built HTML tables. It must be done with CSS only, without relying on JavaScript or events for performance reasons. The challenge is ha ...

What are the steps to prevent a redirect?

I have two forms with different functionalities - one for submitting/adding and the other for selecting/redirecting. Currently, both forms are redirecting. How can I prevent the top form from redirecting after submission? <?php if($_POST){ / ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

After refreshing the page, users are redirected back to the login page

On my website, I created a main page and an index.html page that redirects to the main page through a login panel. The issue I am encountering is that when I log in successfully on the main page and then refresh the page, it takes me back to the login pag ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

Guide on syncing Bootstrap 4 sliders using a single set of controls

Is it possible to synchronize a bootstrap 4 carousel with controls to a carousel without any controls? 1) When the control arrows are clicked, both carousels will slide simultaneously. 2) Hovering over either carousel will pause both carousels from slidi ...

Using node.js to submit a form and upload an image

Seeking some assistance as a newcomer to node. I am trying to achieve a task without the use of any other frameworks like Express. Here is the scenario: I have created a form where users can upload photos to a server running on a node. The form contains t ...

Easy Steps to Align a Rotated Table Header

I am looking to rotate the header table using CSS while keeping all text together. Here is my CSS code: th.rotate { height: 100px; white-space: nowrap; } th.rotate>div { transform: rotate(-90deg); } Here is how I have applied this CSS: ...

methods for extracting header information using JavaScript

Is there a way to retrieve values from the header URL using JavaScript? Consider this scenario: www.example.com/content.html?param=value How can one extract this information upon redirecting to the page content.html? What techniques could be employed f ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

Step-by-step guide on redirecting a page from a Django form

I'm in the process of developing a dictionary application that allows users to input a word through a form. The issue I'm facing is that when a user enters a word and hits submit, the form disappears leaving only the submit button and the search ...

Responsive background image not displaying properly

The developer site can be found at http://www.clhdesigns.com/cliwork/wintermeresod/about.php I am encountering an issue where the background image on the home page scales perfectly, but on the about us page it does not scale at all. I am seeking a solutio ...

An innovative approach to incorporating multiple patterns into HTML input using markup alone, without the need for JavaScript

Input fields are currently set to accept phone numbers in the format 555-555-5555 using the pattern [0-9]{3}-[0-9]{3}-[0-9]{4}. Is it possible to modify the pattern to also allow phone numbers in the format of 5555555555? <input type="tel" cl ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...