Placement of fixed element disrupts the alignment in Bootstrap 4 grid system

I am aiming to create a straightforward layout with a fixed-top navigation bar that spans the full width of the page, and beneath it, two columns (one col-2, the other col-10) that occupy the remaining height. The first column is set to position: fixed because I only want the second column to be scrollable.

Although I managed to achieve this, when I enclose the columns in a container, the fixed column on the left ends up wider than intended:

<div class="container" style="width:50%;">
    <div class="row">
        <div class="col-2 bg-primary" style="position:fixed;">
        Test
        </div>
    </div>
    <div class="row">
        <div class="col-2 bg-primary">
        Test
        </div>
    </div>
</div>

Here's a simple snippet showcasing this issue when one column has a fixed position.

What could be causing this behavior? Is there a way to work around it?

Answer №1

From my perspective, you are looking to have a fixed navbar with two columns below it - one sticky and the other scrollable. Here's a functional snippet to achieve this:

.sticky-top {
  z-index: 9999;
  height:100%;
}

.main {
  top: 56px!important; /*set it according to height of nav bar*/
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>

<body>

  <nav class="navbar navbar-expand-lg bg-dark navbar-dark fixed-top">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
      </ul>
    </div>
  </nav>
  <div class='container-fluid'>
    <div class='row'>
      <div class='col-2 align-self-start sticky-top main'>
       sidebar1
      </div>
      <div class='col-10 main'>
        This main will continue scrolling until the bottom while the sidebar will stick to the top...
        (Text continues in loop for demonstration purposes)
      </div>
    </div>
  </div>

</body>

</html>

Answer №2

If an individual encounters a sticky problem in Internet Explorer and outdated browsers, this JavaScript snippet could offer a viable alternative to using the 'position: sticky' CSS property.

(function($) {
$.fn.sticky = function( options ) {
var settings = $.extend({
stickyTop : 0,
stickyBottom : 0,
widthLimit: 0,
stickyClass: false,
stickyParent: false
}, options);
return this.each( function() {
var $ele = $(this);
var eleTop, eleLeft, eleBottom, eleParBot, eleWid, winWid
var r = function(){
eleTop = $ele.offset().top - settings.stickyTop;
eleLeft = $ele.offset().left;
eleBottom = $ele.offset().top + $ele.innerHeight() + settings.stickyBottom;
$eleParent = $ele.parents(settings.stickyParent) || $ele.parent();
eleParBot = $eleParent.offset().top + $eleParent.innerHeight();
eleWid = $ele.innerWidth();
winWid = $(window).outerWidth();
f();
}
var f = function(){
var winTop = $(window).scrollTop();
if(winTop >= eleTop && winWid > settings.widthLimit){
$ele.css({
'position': 'fixed',
'top': settings.stickyTop,
'left': eleLeft,
'width': eleWid
});
if (settings.stickyClass != false) {
$ele.addClass(settings.stickyClass);
}
if(winTop >= eleParBot-$ele.innerHeight()-settings.stickyTop+settings.stickyBottom){
$ele.css('top', (winTop - eleParBot + $ele.innerHeight() - settings.stickyBottom) * -1);
}
else{
$ele.css('top', settings.stickyTop);
}
}
else{
$ele.removeAttr('style').removeClass(settings.stickyClass);
}
}
r();
$(window).scroll(f);
$(window).resize(function(){
$ele.removeAttr('style');
r();
});
});
}

}(jQuery));
$(document).ready(function() {
$('.header-logo').sticky({
stickyParent: 'body',
stickyTop: 0,
stickyBottom: 0,
stickyClass: 'sticky',
widthLimit: 575
});
});
*, *:after, *:before{
box-sizing: border-box;
}
body {
font-family: 'Open Sans', serif;
background-color: #fff;
padding: 0px;    
height: 1500px;
}
.header-nav{
background-color: #ddd;
}
.header-logo{
background-color: #ccc;
}
.header-logo a{
display: block;
text-align: center;
font-size: 20px;
line-height: 30px;
padding: 20px 0;
color: #1d1d1d;
text-decoration: none;
}
.header-logo.sticky{
background-color: #1d1d1d;
}
.header-logo.sticky a{
color: #fff;
}
.header-navbar{
padding-top: 18px;
padding-bottom: 18px;
}
.header-navbar ul{
margin: 0;
padding: 0;
list-style-type: none;
}
.header-navbar li{
padding: 5px 20px;
}
.header-navbar li:last-child{
padding-right: 0;
}
.header-navbar li a{
color: #1d1d1d;
text-decoration: none;
}
.more-pen{
position: fixed;
right: 20px;
bottom: 20px;
text-align: right;
text-transform: capitalize;
}
.more-pen a{
display: inline-block;
padding: 5px 20px;
background-color: #1d1d1d;
color: #fff;
border-radius: 4px;
text-decoration: none;
transition: all 0.3s ease-in-out;
}
.more-pen a:hover{
background-color: #8647db;
}
.more-pen a .fa{
font-size: 14px;
margin-left: 7px;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container header-nav">
<div class="row align-items-center justify-content-end">
<div class="col-sm-2 header-logo"><a href="#">Logo</a></div>
<div class="col-sm-10 header-navbar">
<ul class="d-flex ml-auto justify-content-sm-end">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">Contact Us</a>
</li>
</ul>
</div>
</div>
</div>
<div class="more-pen">
<a href="https://codepen.io/AsfanShaikh/pen/PrPgZb" target="_blank">For more Stickybar JS demo <i class="fa fa-chevron-right" aria-hidden="true"></i></a>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

What could be causing the alignment issue with cells in Bootstrap?

I'm currently facing an issue with Bootstrap where two columns that are supposed to appear side-by-side on medium resolution end up displaying one below the other. You can view a screenshot of the problem here, and the code can be found at this link. ...

Dividing the background horizontally into two sections with contrasting colors

Is it possible to achieve a background image like this using CSS? https://i.sstatic.net/xS70g.png ...

What is the technique for adding a stroke to an SVG border?

I am in the process of creating a gauge component using SVG. I'm using two strokes to show two states simultaneously. Currently, my output looks like this: enter image description here enter image description here However, I would like it to look li ...

Stylish navigation menu with a subtle scrolling effect in the

Both the left panel and main content should have individual scrolling abilities. You can view a demonstration of this functionality here: http://plnkr.co/edit/Le6hPWwMm0pu5Ukm2cYg?p=preview Below is the CSS code required for this feature: html { ove ...

Don't conceal the :after and :before elements when using CSS custom checkboxes

I have created my own custom checkboxes using this CSS code: input[type="checkbox"]{ display: none; } .checkbox{ position: relative; width: 60px; height: 19px; background-color: green; border-radius: 10px; } .checkbox input[type="checkbox"] + ...

Do you prefer CSS icons or icon images?

I am currently managing a website that contains numerous icons, each of which is associated with a separate image. I have been contemplating the idea of combining all these icons into one image to improve loading speed. However, I am unsure if this would b ...

Steps to eliminate the 'Edit Translation' text on Transposh

Attempting to eliminate the 'Edit Translation' text provided by Transposh to maintain the existing translations. Implementing CSS code like so: #transposh-3:nth-child(8){display:none;} and localizertextnode{display:none;} However, these styl ...

What are the steps to modify my webpage's HTML using 3 separate blocks?

Hey there, I'm looking to customize my HTML layout in the following way: https://i.sstatic.net/mgE1G.png This is what I currently have: <app-list-employees></app-list-employees> <app-book-employee></app-book-employee> <app ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Javascript alert function for confirming background color

Options are displayed in blue, and using JavaScript, I check if the background color is blue. If it's not, execute the next step; otherwise, display an alert message. function click_option_A() { var clr_1_chk = document.getElementById("1"); //alert ...

Adjust the position of an unordered list element in CSS to move it lower on

I have a ul element in my navigation bar at the top of the webpage that I want to adjust slightly downwards. Take a look at the current navigation bar: image To align the text with the white bar at the top of the page, I need to move it down just a bit. ...

The background image refuses to load

I've been working on a website project using nodejs, expressjs, and pug as my template engine. I designed the home page in pure pug but ran into an issue when trying to add a background image to a specific section of the site. Despite double-checking ...

Achieving a full background with Bootstrap 4: the step-by-step guide

Is there a way to ensure that the background completely covers the container? I am working with Bootstrap 4 and have shared my CSS code for the background image below: <div id="form_wrapper" style="background-image:url('img/bg.png&ap ...

Animating changes in Bootstrap column widths and positions within a row

Currently, I am in the process of developing a web application with React and Bootstrap on the frontend. Within the application, there are multiple Bootstrap columns that have the ability to expand. You can see this functionality demonstrated in the CodeSa ...

URL for CSS Background-Image

While working on CSS styling for the body, I ran into a problem and was curious to understand the distinction. Initially, I tried this body { background-image: url('img/bg.png'); } However, it did not produce the desired result. http://www ...

The video attribute in HTML is malfunctioning on the react webpage

Currently working on setting up a basic portfolio layout with a video playing in the background on loop. However, despite making some adjustments and modifications, the video is not showing up as expected. Any insights or suggestions on what might be causi ...

Implementing Vue.js Popover for Individual Dropdown Items: A How-To Guide

I need unique information text to display for each dropdown item when hovered. I am using bootstrap-vue and have a loop set up for the dropdown items. <b-dropdown :text="currentColorType"> <b-dropdown-item v-for="colorType in co ...

Utilize the Bootstrap 4 class to ensure that the navigation brand image is visible solely on medium screens or larger

<header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container"> <a class="navbar-brand" href="#"> <img class="navbar-brand d-none d-md-block" src="img/logo.png"></ ...

Chart: Observing the Discrepancy in the Initial X-Axis Points

I'm working on incorporating multiple charts onto one page, with each chart centered and stacked one after the other. I've set a fixed width for the graph canvas. The challenge arises from the varying ranges of tick values - one chart may have a ...

Changing the navigation bar's position from fixed to static while scrolling using Bootstrap

I am attempting to keep the navbar at the top by setting a fixed position with 'top: 0' on scroll for navbar-default, and return the navbar to its original position when scrolling up (to top 300). Below is my code: var height = jQuery('.n ...