Navbar in Bootstrap

Written by

Hierarchy of Navbar

Navbar
 └── Container
      ├── Navbar.Brand
      ├── Navbar.Toggle
      └── Navbar.Collapse
            └── Nav (ul)
                 ├── Nav.Item        (li; flex item; NOT flex container)
                       └── Nav.Link  (flex container)
                              └── icon + text (aligned by flex)

Navbar attribute

<Navbar expand="lg" className={scrolled ? "scrolled" : ""}>

This scrolled is related to a useEffect() hook

const [scrolled, setScrolled] = useState(false);

useEffect(() => {
  const onScroll = () => {
    if (window.scrollY > 50) {
      setScrolled(true);
    } else {
      setScrolled(false);
    }
  };
  window.addEventListener("scroll", onScroll);
  return () => window.removeEventListener("scroll", onScroll);
}, []);

By which we can get a scrolling effect where the navbar gets smaller and changes background color


Nav

Nav is a flex container, unless rewrite it css

Use me-auto class name to put the first Nav group to the most left

Use ms-auto to the far right

<Nav class="me-auto">
  <!-- Home / Skills / Projects -->
</Nav>

<Nav>
  <!-- Social Icons / Contact -->
</Nav>

Nav.Item & Nav.Link

Always wrap Nav.Link into Nav.Item to keep consistency

Nav.Item is not flex, but Nav.Link is a flex container in default

React Bootstrap’s Nav.Item provides proper list semantics (<li>) for the Nav component (<ul>)


Nav Icon

Bootstrap provides multiple icon and can be accessed by

<i className="bi bi-linkedin"></i>

Nav controls the alignment of Nav.Items but NOT control the alignment of Whatever inside the Nav.Items

Nav Icon acts as a font (inline-text)

Only one icon in one Nav.Link

-> Only use font-size to control the size of the icon while this icon will be centred automatically by flex

Leave a Reply

Discover more from Daily Learning

Subscribe now to keep reading and get access to the full archive.

Continue reading