Extended sticky navigation bar reaching beyond right margin

My website features a navigation bar that is created using the following code:

body {
  margin: 3em;
}
#navbar {
  overflow: hidden;
  background-color: #333;
}
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

Despite setting a margin of 3em for the body, the navbar div appears to extend past the right side of the body. How can I prevent this expansion?

I attempted adding width: 100%; and box-sizing: border-box; to the #navbar CSS rules, but unfortunately, they did not solve the issue. I am running out of ideas for a solution.

Answer №1

Even though the margin affects the fixed navbar, its width is still being defined as 100% of the html, not 100% of the body.

To address this issue, one solution is to utilize the calc() function to deduct the margin (or padding) of the body from the navbar's width.

Check out this jsfiddle where I adjusted your navbar using that method: jsfiddle

I subtracted the margin (from both sides, like the 6em in your case) from the navbar's width.

For further insights, feel free to explore a similar question (same concept but involving padding instead of margin): Position fixed with width 100% is ignoring body padding

Additionally, here's an article offering a comparable solution: CSS padding-right disappear when position fixed width 100%

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

Enforcing Height Constraints on Images in HTML/CSS

I'm currently working on a design project and encountering a minor issue. Feel free to take a look at the final design example linked here: In the menu on both sides, you'll notice a small border that runs from top to bottom, matching the heigh ...

Maximizing the width of navbar elements with Bootstrap 3

I am currently working on building a webpage with bootstrap3, but I have encountered an issue with the navigation bar. I would like the navigation links ("Web Design", "Development", "Photography", "Blog") to be evenly spaced out within the horizontal na ...

Adding multiple images to email HTML with Python made easy

Looking for a solution to embed 15 .jpg images from a single folder into the body of an email without them shrinking when stacked vertically. My initial approach was to create one long image with all photos but it reduced in size as more pictures were adde ...

Creating a persistent gap BETWEEN li inline list items

I'm seeking a solution to create horizontal links using a list. I know that I need to apply the display: block property to the ul element and set display: inline for the li items. While there are several inquiries about maintaining a consistent width ...

Is it possible to design and implement Materialize CSS inputs without relying on Materialize CSS?'

Is there a method to implement Materialize CSS input elements that include placeholders and icons without directly using the Materialize CSS framework? I prefer not to mix frameworks in order to avoid potential conflicts, as I am already utilizing anothe ...

Swift code in WKWebView shows increased word spacing in lengthy Arabic texts

Having long Arabic text within <p> tags in my HTML file (loaded by WKWebView) on my app results in unusually large word spacing and unreadable text. In Xcode, the letters in the HTML file appear disconnected. Is there a way to prevent this issue with ...

Having trouble getting the height to work properly on your Blogger Blogspot template?

Issue with embed height=100% not working <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr"> <head> & ...

Tips on adjusting the dimensions of a switch in kendo UI angular with CSS

Currently, I am utilizing angular in combination with Kendo ui. Is there a way to modify the dimensions of the switch button in Kendo UI Angular using CSS? ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Display the HTML content once the work with AJAX and jQuery has been successfully finished

Below are the codes that I have created to illustrate my question. It's not a complete set of code, just enough to explain my query. The process goes like this: HTML loads -> calls ajax -> gets JSON response -> appends table row with the JSO ...

Examining a V-If using Jest for unit testing

How can I effectively test the v-if condition in my parent component using Jest? Parent Component: <div class="systemIsUp" v-if="systemStatus == true"> foo </div> <div class="systemIsDown" v-e ...

Bizarre Actions of a JavaScript Object

Currently, I am in the process of developing a Multiplayer game using Phaser and Eureca io. My main focus right now is on perfecting the authentication of players and their controls. To achieve this, I have implemented a method on the server that retrieves ...

What is the best method for validating multiple fields in a form with Javascript?

I am currently working on validating multiple fields within a form. Although I lack experience in JavaScript, I have managed to piece together a code that is functional for the most part. If all fields are left blank, error messages prompt correctly. Howe ...

Tips on transitioning between two tables

Recently, I created an HTML page entirely in French. Now, I am attempting to incorporate a language translation feature on the website that allows users to switch between French and English (represented by two flag icons). My concept involves using a tabl ...

Upon loading, the Carousel is visible instead of being hidden, which is contrary to its intended behavior

Any help would be greatly appreciated as I am struggling with creating a web page featuring tabs for "London, New York, Shanghai". The initial page displayed is the "welcome" page with the other tabs hidden on load. I successfully implemented a carousel f ...

When incorporating conditional statements into your code, make sure to utilize the tags <script> along with

I have some script tags as shown below: <script src="cordova-2.5.0.js"></script> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/jquery.mobile-1.1.1.min.js"></script> <script src="js/jquery.xdomainajax ...

The nested ThemeProvider takes priority over the theme's style definitions

Is there a way to render a component and then apply additional rendering using useEffects in React? The issue I am facing is that when I have a component with a specific theme, each useEffect call ends up overriding the style of the original component wit ...

The pictures are not showing up in the photo album

I am currently in the process of building a swim image gallery inspired by the Flex Panel Gallery project from Javascript30 (Repo Link). Upon previewing the site in a browser, I encountered an issue where the images extend beyond the frame, leaving only t ...

Looking for a way to retrieve all HTML tags that have a particular string in their attribute values with Html Agility Pack?

I am currently focused on extracting all HTML tags that have a specific string in their attribute values from the code provided below <meta name="DCSext.oo_market" content="en-us"> <a href="http://office.microsoft.com/en-us/support/" title="Find ...

jQuery is not active on responsive designs

I have implemented a script in my JavaScript code that changes the color of the navigation bar when scrolling. The navigation bar transitions to a white color as you scroll down. However, I am facing an issue with responsiveness and would like to deactivat ...