Rasmi
Rasmi

Reputation: 509

Bootstrap 4 Navbar center align in CSS

I have a Bootstrap 4 navbar in my angular code base, I wanted it to be a bit centre-aligned so that once I move from one menu item to another menu item there are no big gaps.

I have my HTML, TS and CSS below.

My HTML:

<nav class = "navbar navbar-expand-md navbar-fixed-top nav-border" role="navigation">
    <ul class="navbar-nav mx-auto" *ngFor="let menu of menus">
        <li class="nav-item dropdown">
            <a class="nav-link" data-toggle="dropdown" data-target="{{menu.heading}}">{{menu.heading}}</a>
            <div class="dropdown-menu" aria-labelledby="{{menu.heading}}">
                <a *ngFor="let option of menu.options" href="{{option.link}}" target="_blank" class="dropdown-item">{{option.name}}</a>
            </div>
        </li>
    </ul>
</nav>

My TS:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-top-menu',
  templateUrl: './top-menu.component.html',
  styleUrls: ['./top-menu.component.css']
})
export class TopMenuComponent implements OnInit {

  menus : any = [
    {
      
        heading: "MENU1",
        options: 
        [
          {name: "GOOGLE",link: "https://google.com/", order: 1},
          {name: "GitHub",link: "https://github.com", order: 2},
        ]
      
    }
  ];
  
  isDropdownOpen: boolean = false;
  constructor() { }

  ngOnInit(): void {
  }

}

My CSS:

.navbar{
    padding:0px;
}
.nav-border {
    border-bottom:1px solid #ccc;
}
li { cursor: pointer; }

li:hover{
    background-color: black;
}

a {
    color: black;
}

.navbar-nav {
    padding: .9rem 0 0;
}

.nav-link:hover {color:white;}

.widthd{
    width: 100%;
}

My screen:

enter image description here

Now the menu is spread far apart, I wanted them to be a bit closer and in the centre of the screen.

Upvotes: 0

Views: 53

Answers (1)

rensothearin
rensothearin

Reputation: 756

You can try this:

<nav class = "navbar navbar-expand-md navbar-fixed-top nav-border" role="navigation">
  <div class="container"
    <ul class="navbar-nav mx-auto" *ngFor="let menu of menus">
        <li class="nav-item dropdown">
            <a class="nav-link" data-toggle="dropdown" data-target="{{menu.heading}}">{{menu.heading}}</a>
            <div class="dropdown-menu" aria-labelledby="{{menu.heading}}">
                <a *ngFor="let option of menu.options" href="{{option.link}}" target="_blank" class="dropdown-item">{{option.name}}</a>
            </div>
        </li>
    </ul>
  </div>
</nav>

The solution is to put <div class="container" to wrap the <ul></ul>. Or if you want to customize it to be more center, you can add CSS like this:

.container-custom {
  width: 70%
}

Then you can change the container class in into container-custom.

Upvotes: 3

Related Questions