Bootstrap 4 and the benefits of fixed position menus

I've decided to dive into learning CSS, HTML, and JavaScript by building a dashboard from scratch instead of taking the easier route of purchasing a pre-made Bootstrap dashboard UI. However, I've run into an issue that's proving challenging to solve. My goal is to have a fixed position for both the sidebar menu and the top menu so they stay static on the screen. But when I implement this, the content div shifts underneath the menus. I know I can add margin to reposition them, but even then, if I include a toggle button to expand the sliding menu, how should I handle the horizontal shift? Here is a link to the JSFiddle where I'm working on it:

https://jsfiddle.net/4x60gqsn/

Thank you, Shaun

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Collapsible sidebar using Bootstrap 4</title>

    <!-- Bootstrap CSS CDN -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
    <!-- Our Custom CSS -->
    <link rel="stylesheet" href="css/style.css">

    <!-- Font Awesome JS -->
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>

</head>

<body>

    <div class="wrapper">
        <!-- Sidebar  -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <img class="nav-logo" src="../login/images/PrintPerry.png">
                <strong>PP</strong>
            </div>

            <ul class="list-unstyled components">
                <li>
                    <a href="#">
                        <i class="fas fa-home"></i>
                        <span class="nav-text">
                            HOME
                        </span>
                    </a>
                </li>
                <li>
                    <a href="#">
                        <i class="fas fa-home"></i>
                        <span class="nav-text">
                            TEST
                        </span>
                    </a>
                </li>
            </ul>
        </nav>

        <!-- Page Content  -->
        <div id="content">

            <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">

                    <a href="#" id="sidebarCollapse">
                        <i class="fas fa-align-justify fa-lg" ></i>
                    </a>
                    <span>
                        <a href="#" class="profile-btn">
                            <i class="fas fa-user fa-lg"></i>
                        </a>
                        <a href="#" class="profile-btn">
                            <i class="fas fa-envelope fa-lg"></i>
                        </a>
                    </span>
                </div>
            </nav>
            <div class="content-wrapper">
                <h2>Collapsible Sidebar Using Bootstrap 4</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

                <div class="line"></div>

                <h2>Lorem Ipsum Dolor</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

                <div class="line"></div>

                <h2>Lorem Ipsum Dolor</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis not ...

Answer №1

If your goal is to keep the navbar in place when scrolling, you can achieve this using position:fixed.

An alternative and cleaner method is to use position: sticky;. You can see an updated example on this Fiddle.

$(document).ready(function() {
  $('#sidebarCollapse').on('click', function() {
    $('#sidebar').toggleClass('active');
  });
});
/* DEMO STYLE */

@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";
body {
  font-family: 'Poppins', sans-serif;
  background: #fff;
}

p {
  font-family: 'Poppins', sans-serif;
  font-size: 1.1em;
  font-weight: 300;
  line-height: 1.7em;
  color: #999;
}

...

Answer №2

If you're looking to ensure compatibility across all browsers, consider following the bootstrap approach. Set the body padding-top equal to the height of the header and padding-left to the width of the sidebar. Use position-fixed for both the header and sidebar elements. For example, if the header is 60px in height, specify the body's padding-top as 60px.

body, html {
  height: 100%;
}

.width-100px {
  width: 100px;
}

.fixed-left {
  left: 0;
}

body {
  padding-top: 56px;
  padding-left: 100px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<header class="fixed-top">
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <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 dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Something else here</a>
          </div>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">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>
  </nav>
</header>
<aside class="position-fixed fixed-left bg-danger width-100px h-100">

</aside>
<main class="container-fluid bg-primary text-white">
  <div class="row">
    <div class="col">
      <p>
        <span>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nostrum fugiat delectus, ea vitae iure reprehenderit quaerat, mollitia ipsam id qui nesciunt, officiis corporis quod! Aspernatur est velit exercitationem unde fuga.</span> 
	<!-- Other lorem ipsum content -->
      </p>
    </div>
  </div>
</main>

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

The issue arises when the view fails to load while simulating a backend

Trying to test a specific element of the user interface requires a particular request to the backend with predefined data while allowing all other requests to pass through. Here's a more readable version in coffee script: describe 'select2 combo ...

How can I modify the custom CSS to adjust the color of a Font Awesome icon?

Hello everyone! I am new to coding and I have a question for the Stack Overflow community. I am trying to customize the color of my Font Awesome icons on the homepage of my WordPress theme (Arcade Pro) using the custom CSS editor. Can anyone provide me w ...

Tips for building a MongoDB document that includes both objects and arrays, along with the corresponding schema in Mongoose

Need assistance with saving data in a mongodb database such as the following: { name: "Just a name", questions: [ { question: "Question 1", answerOptions: [ {id: 0, text: "answer 1"}, ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Using the array `$_POST` by combining multiple pieces of data into a

Is it possible to receive arrays in $_POST without multiple hidden input fields and without using ajax to submit the form? Typically, I would set up the HTML like this: <input type="hidden" name="array[]" /> <input type="hidden" name="array[]" / ...

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...

Can information be saved to a JSON file without using a server-side language?

Previously, I've come across questions where the recommended solution involves using a server-side language. However, since I don't have knowledge of a server-side language yet, I was curious to know if it's possible to achieve this with my ...

Error encountered while trying to load component: template or render function is not defined

I have set up a basic vue.js configuration using browserify and vueify. Following advice from previous tutorials, I included aliasify as a dependency to utilize the template engine. Below is my package.json file: { "name": "simple-vueify-setup", "ve ...

JavaScript function is not callable

Currently facing a strange issue or maybe it's just me missing something obvious. I've searched for the error but couldn't find the right solution. I am attempting to execute some Javascript code when the key "/" is pressed in a text box. ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

Enhance your website with a stylish CSS jQuery menu that lets you toggle, slide

If you're curious about the code, take a look here! Here are some of the issues I'm facing: The div doesn't toggle to hide when clicked on itself, only when another one is clicked. (UPDATE: it actually won't toggle at all) When t ...

The Ajax response is revealing JavaScript instead of concealing it

Currently, I am developing a comment system with various features such as deleting the main post, deleting comments, deleting replies, editing the main post, editing comments, editing replies, and implementing Read More/Read Less for posts longer than 250 ...

Transfer the File object to background.js from the content script, or transmit the createObjectURL and maintain its persistence even after refreshing

My main objective is to execute an in-background file upload task using a file obtained from the content script. I have come to realize that passing a File object directly from the content script to the background is not feasible, as chrome.runtime.sendMe ...

Guide on how to gather values into a variable from the DOM using jQuery

Trying to make this function: The current issue I'm facing is that when changing a digit (by clicking on a hexagon), I want to save the selected number as the value of a hidden input field next to the digit in the DOM. Any ideas on how to achieve th ...

Looking for some guidance with Bootstrap column layouts

I'm in the process of creating an address field layout. My goal is to have the State and Country sections positioned on the right side of the city and postal code fields. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3 ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

Tips for positioning and resizing an HTML slide

Once again I am faced with my favorite HTML/CSS dilemma and am feeling frustrated. Seeking advice from the experts on SO this time around to solve my problem. Here it is... Imagine you want to create a slideshow in a browser. The requirements are simple: ...

Encountering a display issue with Facebook page iFrame on a Bootstrap Template when integrating Laravel as the backend for embedding the iFrame

I am currently using a bootstrap template and I would like to showcase a Facebook page iFrame within the sidebar. The iFrame code I am utilizing is generated by the Facebook Page Plugin. Below is the code: <iframe src="https://www.facebook.com/plugins/ ...