Applying right margin to the nav bar without causing issues with the navbar collapse in Bootstrap - how to do it?

Objective:

The goal is to adjust the position of the navigation bar items using padding or margin as indicated in red:

https://i.sstatic.net/5vYTc.png

Issue

I noticed that applying a right padding or margin affects the collapsed (on mobile screen) list items with additional right margin or padding.

Here's an exaggerated example of excessive padding:

https://i.sstatic.net/KrKpC.png

Desired Outcome:

This is the desired layout:

https://i.sstatic.net/4g9fL.png

And, ensuring centered collapsed list items in responsive mode:

https://i.sstatic.net/XE8hm.png

Code Snippet:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 20px;
 }

.navbar {
  background-color: black !important;
}

.navbar .navbar-collapse li{
  text-align: center;
  margin-bottom: 20px;
}

.navbar-nav > li{
  padding-right:30px;
}

.navbar li a {
  text-decoration: none;
  text-transform: uppercase;
  font-size: 70%;
  color: #000;
}

.navbar ul li a {
  position: relative;
  z-index: 1;
  padding: 15px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8>
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Vollkorn&display=swap" rel="stylesheet">
    <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
  </head>
  <body>


    <header>
          <nav class="navbar navbar-expand-lg navbar-dark bg-light">
            <button class="navbar-toggler">
              <span class="navbar-toggler-icon" data-toggle="collapse" data-target="#navbarMenu"></span>
            </button>
            <div class="collapse navbar-collapse justify-content-end" id="navbarMenu">
              <ul class="navbar-nav">
                <li class="nav-item"><a href="#">Home</a></li>
                <li class="nav-item"><a href="#">About me</a></li>
                <li class="nav-item"><a href="#">Projects</a></li>
                <li class="nav-item"><a href="#">Contact me</a></li>
              </ul>
            </div>
          </nav>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56868883889d808cc68ec7e6f98689079989952af848882fd918c8a">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  </body>
</html>

Inquiry

What would be an effective solution to achieve the specified design outcome?

Answer №1

To achieve the desired result, simply append these media queries at the end of your CSS file. You have the freedom to specify the number of pixels for margin-right: 100px;. Additionally, include padding-right: 0; to eliminate indentation on mobile devices and enhance menu centering.

@media (min-width: 992px) {
  .navbar-expand-lg .navbar-nav {
      margin-right: 100px;
  }
}

@media (max-width: 992px) {
  .navbar-nav > li {
      padding-right: 0;
  }
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 20px;
 }

.navbar {
  background-color: black !important;
}

.navbar .navbar-collapse li{
  text-align: center;
  margin-bottom: 20px;
}

.navbar-nav > li{
  padding-right:30px;
}

.navbar li a {
  text-decoration: none;
  text-transform: uppercase;
  font-size: 70%;
  color: #000;
}

.navbar ul li a {
  position: relative;
  z-index: 1;
  padding: 15px;
}

@media (min-width: 992px) {
  .navbar-expand-lg .navbar-nav {
      margin-right: 100px;
  }
}

@media (max-width: 992px) {
  .navbar-nav > li {
      padding-right: 0;
  }
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Vollkorn&display=swap" rel="stylesheet">
    <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
  </head>
  <body>


    <header>
          <nav class="navbar navbar-expand-lg navbar-dark bg-light">
            <button class="navbar-toggler">
              <span class="navbar-toggler-icon" data-toggle="collapse" data-target="#navbarMenu"></span>
            </button>
            <div class="collapse navbar-collapse justify-content-end" id="navbarMenu">
              <ul class="navbar-nav">
                <li class="nav-item"><a href="#">Home</a></li>
                <li class="nav-item"><a href="#">About me</a></li>
                <li class="nav-item"><a href="#">Projects</a></li>
                <li class="nav-item"><a href="#">Contact me</a></li>
              </ul>
            </div>
          </nav>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43332c333326316d293003726d72756d72">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  </body>
</html>

Answer №2

To achieve this, you have a couple of options:

  1. To add margin to the right of your navbar on larger screens using media queries, you can use the following code snippet which applies CSS only for screens 992px or wider:
@media (min-width: 992px) {
    #navbarMenu { margin-right: 200px; }       
}

View working example:

[Working example code here]

  1. You can also set a max-width on your navbar so that space is added equally to both sides once the screen reaches a certain width, like this:

    nav { margin:auto; max-width: 400px; }

Since the background color is applied to `nav`, you can fill the rest of the screen with this color by using a wrapper class or just utilizing `header if it contains nothing else except the nav. Applying the Bootstrap `bg-light` class helps match the navbar's style.

<div class="wrap bg-light">
    <nav class="navbar navbar-expand-lg navbar-dark bg-light">
        [rest of your code here...]
    </nav>
</div>

Utilizing a wrapper ensures an equal amount of spacing on both sides and increases as the screen widens. It may seem excessive to add another wrapper, but it standardizes width consistency across all content and allows easy reuse for multiple sections while maintaining smooth layout transitions.

View working example:

[Another working example code here]

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

Can this PHP code be optimized for better efficiency?

Seeking to create dynamic links on a page where the link for the current page is excluded. The code functions as desired but seems repetitive - hoping for a more efficient solution, given limited programming experience. <div class= "links"> <?php ...

Is there a way to turn off Emmet's CSS Abbreviations feature in Sublime Text 2?

One thing I really enjoy is how Emmet can generate HTML using 'CSS-like' strings. However, I prefer not to use their CSS Abbreviations. For example, when I write the following line of CSS: li a| I expect to get a tab when I press 'TAB&apos ...

Is it possible to size a child div to be larger than its parent without using absolute positioning?

I'm trying to figure out a way to have one or two divs on a page that are larger than their parent div without having to overhaul the entire website structure. I originally considered using position absolute, but that would mess up the container heigh ...

The ball refuses to fall into the designated boxes

I designed a basic webpage featuring 3 boxes that, when clicked on, trigger the dropping of a ball into them. Below is the code I used: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function popup (n) { ...

What is the most effective way to store HTML templates on a webpage?

As I work on developing a complex JavaScript interface for my website, I have decided to utilize the jQuery templates plugin to create elements based on queries to a JSON API. However, I am faced with an issue: I anticipate needing numerous templates for ...

Overflow-y SweetAlert Icon

Struggling with a website modification issue where using Swal.fire(...) causes an overflow problem affecting the icon rendering. How can this be fixed? Here is the custom CSS code in question: * { margin: 0px; padding: 0px; font-family: &ap ...

Harvesting data from an HTML document using BeautifulSoup and Python

I am currently working on extracting text from an HTML file. The HTML file has the following structure: <li class="toclevel-1 tocsection-1"> <a href="#Baden-Württemberg"><span class="tocnumber">1</span> <span class= ...

"Google Chrome v84 does not render elements with zero height, line-height, and display: flex correctly

In Google Chrome v84, there seems to be an issue with line-height and display: flex (Chrome v83 and FireFox are not affected). The height of the element is not always enforced properly. <div class="outer-wrapper"> <div class="wrap ...

Struggling to get Angular to properly load routes

I've been working on a local web page recently, following this helpful tutorial that shows how to integrate Django and Angular for user authentication. However, I've encountered an issue where the "register" button doesn't display anything e ...

Resize the div based on the width and height of the window

My goal is to create a system or website that can be fully resizable using CSS and the VW (viewport width) unit. Within this system, I have integrated a GoogleChart that functions with pixels. Now, I am looking for a way to scale the chart using Javascript ...

Tips for stopping the background color from affecting the text color

I'm dealing with a situation where I have an h6 nested inside a div. <div class="cylinder" data-v-5147e140=""> <div data-v-5147e140=""> <h6 class="quantite" data-v-5147e140="&qu ...

Is it possible to utilize CSS rules for a non-existent div within CSS?

Can this be achieved using CSS? If .div1 is not present, enforce the following rule: .div2{ property: value; } For example, <div class="div1"> ... </div> <div class="div2"> <!-- it exists, so no action needed --> </div& ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

How about having one row with five divs of equal width, each with a margin-right of 20px?

Is there a way to achieve 5 floating divs on one row with a 20px margin-right between each, except for the last-child? This is the desired structure: <div class="f-item pull-left">1</div> <div class="f-item pull-left">2</div> < ...

The Best Practices section of the Chrome lighthouse report has identified an issue with properly defining the charset

I recently noticed an error in my VueJs SPA application when running a Chrome Lighthouse report. The error message indicated that the charset was not properly defined, even though I had added it to my index.html file. Below are screenshots of the issue: ...

Issue arising from background-image and content property size

.section--7__photos { height: 50vw; max-height: 70rem; margin: 0 8%; background: url("https://ableton-production.imgix.net/about/photo-8.jpg?crop=right&dpr=1.5&fit=crop&h=250&ixjsv=1.1.3&q=66&w=417") no-repeat top 0% center/ ...

Ensure that only one checkbox is checked at a time and that unchecking one does not remove the

https://i.sstatic.net/EEC2U.png I am facing an issue with two checkboxes in my code. When I click on the first checkbox in the featured playlist section, another popular genre checkbox should be unchecked. However, only the value changes and the checked m ...

YouTube videos cannot be embedded using an iframe on Firefox

I inserted a YouTube iframe code inside a div element. <div id="box"> <iframe width="300" height="315" src="//www.youtube.com/embed/82fn4mcNGJY" frameborder="0" allowfullscreen></iframe> </div> After applying CSS to sc ...

Simple method to retrieve unordered list identifiers as an array using PHP

Currently, I am working with an unordered list where I am using DB ids as the list-item ids. When the Submit button is pressed, I want to present all the ID's of my list items as an Array in PHP. I am still learning JavaScript and although there are s ...

Smooth-scrolling feature with touch interaction available in the scrollbar extension

Anyone here aware of a high-quality jQuery or CSS plugin for scrollbars that supports touch functionality and smooth easing? I've been on the lookout for one, but haven't had any luck so far. Even if it comes with a price tag, I'm interested ...