Updating navbar in Bootstrap 4.5 to accommodate limited space

Snippet of Code (With Bootstrap 4.5):

$(".self-first-ul").append('<li class="nav-item">A lengthy sentence that is too long for small screens.</li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar sticky-top navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="http://localhost/project/">Name</a>

  <ul class="navbar-nav self-first-ul">
  </ul>

  <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 ml-auto">
      <li class="nav-item">
       <a class="nav-link" href=""><img src="" alt="" title="" width="30" height="30" loading="lazy" />&nbsp;
          <span>1</span>
        </a>
      </li>
    </ul>
  </div>
</nav>

Display on Large Screen:-

Display on Small Screen:-

Preferred Design for Small Screens:-

I attempted to add an additional navbar below the first one, however, it did not align well on large screens and caused overlap on small screens.

Answer №1

I have made updates to the jquery code to fulfill your requirements. Please execute the code snippet below for more information.

$(document).ready(function() {
  $(".self-first-ul").append('<li class="nav-item">A lengthy sentence that may not be suitable for small screens.</li>');

  function updateFlexConfiguration(x) {
    if (x.matches) { // If media query matches
      $("nav").css("display", "flex");
      $("a").css("order", 0);
      $("button").css("order", 1);
      $("ul").css("order", 2);
    } else {
      $("nav.navbar").css("display", "flex");
      $("a").css("order", 0);
      $("ul").css("order", 1);
      $("button").css("order", 2);
      $("div").css("order", 2);
    }
  }
  const navBarPadding = 32;
  var navItemsWidth = $("a").outerWidth(true) + $("button").outerWidth(true) + $(".self-first-ul").outerWidth(true) + navBarPadding;
  var x = window.matchMedia("(max-width: " + navItemsWidth + "px)");
  updateFlexConfiguration(x); // Execute listener function during runtime
  x.addListener(updateFlexConfiguration); // Connect listener function to state changes

});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


<nav class="navbar sticky-top navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="http://localhost/project/">Name</a>

  <ul class="navbar-nav self-first-ul">
  </ul>

  <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 ml-auto">
      <li class="nav-item">
        <a class="nav-link" href=""><img src="" alt="" title="" width="30" height="30" loading="lazy" />&nbsp;
          <span>1</span>
        </a>
      </li>
    </ul>
  </div>
</nav>

Update: To center the long text

$(document).ready(function() {
  // Added text-center to align the text in the middle
  $(".self-first-ul").append('<li class="nav-item text-center">A lengthy sentence that may not fit on smaller displays.</li>');

  function updateFlexConfiguration(x) {
    if (x.matches) { // If media query matches
      $("nav").css("display", "flex");
      $("a").css("order", 0);
      $("button").css("order", 1);
      $("ul").css("order", 2);
      $("ul").css("flex-grow", 1); // Expand to utilize remaining space and center text
    } else {
      $("nav.navbar").css("display", "flex");
      $("nav.navbar").css("justify-content", "space-between"); // Adjust spacing between flex-items
      $("a").css("order", 0);
      $("ul").css("order", 1);
      $("ul").css("flex-grow", 0); // Prevent ul from expanding into remaining space
      $("button").css("order", 2);
      $("div").css("order", 2);
      $("div").css("flex-grow", 0); // Set div not grow with the remaining space
    }
  }
  const navBarPadding = 32;
  var navItemsWidth = $("a").outerWidth(true) + $("button").outerWidth(true) + $(".self-first-ul").outerWidth(true) + navBarPadding;
  var x = window.matchMedia("(max-width: " + navItemsWidth + "px)");
  updateFlexConfiguration(x); // Call listener function at run time
  x.addListener(updateFlexConfiguration); // Attach listener function on state changes

});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


<nav class="navbar-sticky-top navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="http://localhost/project/">Name</a>

  <ul class="navbar-nav self-first-ul">
  </ul>

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="SupportedContent" aria-expanded="falsig" aria-label="Toggle Navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

  <div class="collapsed navbar-collapse" id="SupportedContent">

    <ul class="navbar-nav ml-adapt">
      <li class="nav-stationary">
        <a class="nav-anchor" comparativethickness="" alt="" titling="" width="30" height="30" loading="lazy" />&nbsp;
          <span>1</span>
        </a>
      </li>
    </ul>
  </div>
</nav>

Answer №2

If you want to display or hide specific elements in your HTML based on the responsive utilities offered by bootstrap documentation, check out: https://getbootstrap.com/docs/4.5/utilities/display/

Take a look at "d-none d-md-block d-xl-block" or "d-block d-sm-block d-xs-block d-md-none d-lg-none d-xl-none" for reference....

The example below may help address your requirements to some extent, but feel free to experiment with it to find the perfect solution:

    <div class="container">
  <div class="row">
    <div class="col">
      <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>

        <!-- Visible on larger screens -->
        <div class="d-none d-md-block d-xl-block">Header for md + xl viewports</div> 

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarTogglerDemo02">
          <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="#" 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">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
          </form>
        </div>
      </nav>      

      <!-- Visible on smaller screens -->
      <div class="d-block d-sm-block d-xs-block d-md-none d-lg-none d-xl-none">Header for sm + xs viewports</div>
    </div>
  </div>
</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

Design a sophisticated background using CSS

https://i.sstatic.net/yILwL.png I am wondering if there is a way to create a CSS3 background similar to the one shown in the image link above. The gradient should smoothly transition from white to black, spanning across a header div, and remain consistent ...

What measures can I take to hide the browser's rendering of an image?

I've noticed that when I insert new images into the DOM, occasionally I can observe the image being displayed in a top to bottom manner. Is there a simple JavaScript method or event handler that I could utilize to ensure that the entire image only app ...

The presence of a .js file is causing a blockage in the loading

As a beginner in the world of jquery/web design, I decided to download a template to experiment and get more familiar with it. Unfortunately, I encountered an issue with a specific script that is causing my jQuery to not load properly. Here is the snippet ...

"Exploring the Relationship Between Parent and Child Elements in CSS

Is it possible for an id to act as a parent in CSS? For instance: <div id="link"> <a href="www.example.com"></a> </div> The CSS code: #link > a{ /* style would be applied here*/ } Can this actually be achieved? ...

Is it possible to create an AngularJS and jQuery Calendar Directive that activates by clicking on a Bootstrap glyphicon?

I have successfully created a directive for my calendar using AngularJS and jQuery. The datepicker pops up when the user selects the input box. Now, I am attempting to allow the user to click on Bootstrap's 'glyphicon glyphicon-calendar' to ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

Create a dynamic menu dropdown with absolute positioning using React

I recently made the transition to React and now I am in the process of converting my old vanillaJS website into ReactJS. One issue I am facing is with a button that is supposed to trigger the opening of a dropdown menu. <button type="button&qu ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

How do you use CSS to replace an HTML "rules" attribute?

When publishing to HTML using the DITA Open Toolkit, certain inline table attributes are automatically applied such as frame="border" and rules="all". I am facing an issue where I need to override the "rules" attribute for table cells using CSS styles. Wh ...

Transferring information from HTML to C#, a seamless process

Utilizing this specific HTML code (based on bootstrap) allows users to input tags in a neat manner: <div class="bootstrap-tagsinput"> <span class="tag label label-info">test tag<span data-role="remove"></span></span> <span ...

Hover over the entire row to see it light up

I am trying to create a JavaScript function that loops through a variable number of iterations and dynamically generates HTML elements on the DOM / Webpage. Once the loop is complete, it populates the following div: <div class="energyRowContainer" id ...

Is there a way to generate PDF files from rrdcgi output?

I have developed an rrdcgi script to showcase system performance data through graphs. I am now seeking a way to allow users to generate PDFs on the spot, containing the current page's images and information along with header and footer details. Additi ...

What is the best way to align the bottom of an element with the browser buttons panel on mobile devices?

When viewing the website on a mobile device, I noticed that the floating button is hidden behind the browser buttons panel. Is there a way to adjust the positioning of the element relative to the browser's buttons panel? I attempted using env(safe-ar ...

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

I am looking to implement screen reader capabilities for both the select-2 combo box and bootstrap's datetime-picker. How can I go about doing

On my existing website, I have select-2 combo boxes for drop-down lists and a Bootstrap Calendar widget. While these features work well, they lack accessibility for users with disabilities. In an effort to make the website inclusive for everyone, I am work ...

Adjust the minimum height and width when resizing the window

Apologies in advance if this has already been addressed, but I have tried solutions from other sources without success. My Objective: I aim to set the minimum height and width of a div based on the current dimensions of the document. This should trigger ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Bringing back a string from an external Ajax call

Learning something new can be challenging, so please bear with me: I've set out to create an image gallery that features a main index page where users can select various project categories, a sub-index page for selecting specific projects within the ...

Bootstrap for a more streamlined container

https://i.sstatic.net/fJ8nt.png My Bootstrap setup includes a container-fluid with multiple cards inside. I want to adjust the container layout to stack the cards more closely together in a vertical direction, instead of being displayed in a grid format. ...

Issue with fluid layout in CSS - Unable to specify height in pixels and minimum height property not functioning as expected

While working on a liquid layout, I have set all my width and height values in percentages. However, during the design process, I needed to check how my CSS was rendering so I temporarily set the height in pixels. Eventually, the height in percentage wil ...