Having trouble with Bootstrap 4 maintaining consistent width when affixing the sidebar

Hello there, I'm currently working with Bootstrap 4 and trying to implement affix on the sidebar. I have set up three columns for the sidebar and made them fixed under certain conditions. However, I am facing an issue where the width of the sidebar changes when it is affixed. My goal is to maintain the same width for the sidebar whether it's in its normal state or affixed. Any assistance on this matter would be greatly appreciated. Thank you in advance! Please note: Kindly view the fiddle in desktop mode.

var toggleAffix = function(affixElement, scrollElement, wrapper) {

  var height = affixElement.outerHeight(),
    top = wrapper.offset().top - 58;

  if (scrollElement.scrollTop() >= top) {
    wrapper.height(height);
    affixElement.addClass("affix");
  } else {
    affixElement.removeClass("affix");
    wrapper.height('auto');
  }

};


$('#top-affix').each(function() {
  var ele = $(this),
    wrapper = $('<div></div>');

  ele.before(wrapper);
  $(window).on('scroll resize', function() {
    toggleAffix(ele, $(this), wrapper);
  });

  // init
  toggleAffix(ele, $(window), wrapper);
});
body {
  padding-top: 3.625rem;
}

.container-fluid {
  max-width: 1300px;
}

.projects-wrp .title {
  background-image: -webkit-gradient(linear, left bottom, right top, from(#0a0b0c), color-stop(#121315), color-stop(#17191b), color-stop(#1d1f22), to(#222529));
  background-image: linear-gradient(to right top, #0a0b0c, #121315, #17191b, #1d1f22, #222529);
  color: #fff;
  padding: 0.75rem;
}

.projects-wrp .title h2 {
  font-size: 1.5rem;
}

.projects-wrp .affix {
  position: fixed;
  top: 3.625rem;
  right: 0;
  left: 0;
  z-index: 1030;
}

.projects-wrp .sidebar-lft h4 {
  font-size: 1.125rem;
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6J..." crossorigin="anonymous">
</head>

<body class="projects-wrp" style="height: 1500px;">
  <nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
      <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
        <a class="navbar-brand" href="#">Hidden brand</a>
        <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Link</a>
          </li>
          <li class="nav-item">
            <a class="nav-link disabled" href="#">Disabled</a>
          </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
      </div>
    </div>
  </nav>
  <div class="title">
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-12">

          <h2 class="mb-0"> Avacadu.com[Onpage Seo Only]</h2>
        </div>
      </div>
    </div>
  </div>
  <main>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4 col-xl-3" id="top-affix">
          <aside class="sidebar-lft affix-container" style="background: #ccc;">
            <h4><i class="fas fa-clipboard-list"></i> Categories</h4>
            <p class="mb-0">
              <a class="" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                            Link with href
                          </a>
            </p>
            <div class="collapse" id="collapseExample">
              <div class="card card-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
              </div>
            </div>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
            <p>sdfghjkliutrsdfgh</p>
          </aside>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8 col-xl-9">

        </div>
      </div>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></scri...

Answer №1

When the sidebar is set to position:fixed, it loses its ability to maintain a relative (%) width within the DOM flow. It becomes affixed to the viewport, separate from other elements on the page. This issue has been discussed in various threads on the topic.

To address this, you need to assign a specific width to the affixed element:

#top-affix {
  max-width:300px;
}

For those interested, here is a link for more information:

If you prefer to keep the sidebar's width as a relative percentage, consider using position:sticky instead of position:fixed.


Related:
Inheriting width from Bootstrap container when child is position fixed
How to create a sticky left sidebar menu using bootstrap 3?
Set width of a "Position: fixed" div relative to parent div

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

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

Importing the class results in an undefined outcome

In the process of developing my Vue app, I'm focusing on creating some helper classes: File a.js: export default class Base {//...} File b.js: import Base from "./a" export default class Middle extends Base { // ... } File c.js: import Mi ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Navigate through content easily using the arrow keys on your keyboard with the help of Easy Slider

I'm attempting to modify the Easy Slider in order to enable navigation of the slideshow with the arrow keys on the keyboard. I made adjustments to the javascript's animate function, changing it from: default: t = dir; break; ...to: default: t ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Chil ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

The arrangement of elements varies based on the type of display

I'm still learning HTML and CSS, and I've noticed that the layout of my elements changes depending on the screen size. Everything looks good on my 24" monitor, but some elements overlap on my 15" laptop screen. What could be causing this issue, ...

React.js: Dynamically Highlighting Menu Items Based on Scrolling位置-GaidoWhen a

Having trouble finding a solution for this issue. I'm currently working on creating a navigation bar with scroll-to functionality, where clicking on a menu item scrolls the page to the corresponding section. However, I am unsure how to change the colo ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...

Issue with OpenLayers Icon not appearing on screen

I just finished creating a SpringBoot app using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and packaging it as an executable JAR file. Within this app, I have integrated OpenLayers 4 library to display a map with an Icon. Howeve ...

What are the steps to incorporating ng2-dnd with a background-image?

I am currently utilizing the ng2-dnd module to enable sorting of a list. While the functionality for sorting and dragging is working smoothly, there's one issue - users can only drag by clicking on the text within my element. My goal is to allow user ...

What is the best way to connect a CSS file with multiple pages located within a specific folder in HTML/CSS?

In my CS 205 class project, I am tasked with creating a website. To accomplish this, I used Notepad++ for the HTML files and Notepad for the CSS files. The site consists of an index.html page along with other content pages, each designed separately in Note ...

Expand the table in the initial state by using CSS to collapse the tree

I am struggling to collapse the tree view and need assistance. Below is the code snippet I've added. My goal is to have each node in the tree view initially collapsed and then expand a particular node on user interaction. For example, when I execute ...

The fixed element alters its color when applied to a specific class within a div

I have a button with an icon and text that remains fixed on my webpage. The background colors of the sections change as you scroll through them, alternating between dark and light. I am looking for a solution where I can apply a class to multiple section ...

Puppeteer challenge with breaking images

When generating a PDF from HTML, I am facing an issue where the signature image breaks on another page. Is there a way to ensure that if content or images break, they will move to another PDF page? Puppeteer version - 3.3.0 Node version - 12.16.1 Check t ...

Ways to minimize the space between elements in a flex container

My goal is to minimize the space between my images that expand on hover. I aim for it to resemble this: expectation However, the current appearance is more like this: reality This is what I currently have: .container { display: flex; width: 100 ...