How to create a Header in Tailwind CSS

H
andrewgbliss
17 days ago

This article will cover how to create a Header using Tailwind CSS

. . .

Github Repo

https://github.com/LevelUpDevTraining/tailwindcss-workshop

Header component

This is the main component for the header bar. We start off using a header html tag, then use a tailwind css flex class to show the sub components of the logo, the search, and the nav.

import Logo from './Logo';
import Nav from './Nav';
import Search from './Search';

export default function Header() {
  return (
    <header className="bg-black text-white">
      <div className="flex justify-between items-center p-2">
        <div className="flex-grow">
          <Logo />
        </div>
        <div className="pr-2">
          <Search />
        </div>
        <div>
          <Nav />
        </div>
      </div>
    </header>
  );
}

Logo

This is super simple for now. However you can add an image or any text here you like for the logo.

export default function Logo() {
  return (
    <>
      <a href="/">Logo</a>
    </>
  );
}

Search

This is also super simple for now. In later articles we will go over how to make a more robust search and advanced search.

export default function Search() {
  return (
    <>
      <input
        type="text"
        name="search"
        id="search"
        value=""
        placeholder="... search"
      />
    </>
  );
}

Navigvation

This is the more complex component in the header as of now. If will show the normal links on small and above screens, and on mobile it will hide the normal links and show a hamburger menu with a nav drop down.

import { useState } from 'react';
import MenuIcon from '@components/Icons/Menu';

function Links() {
  return (
    <>
      <a className="block pr-2" href="/about">
        About
      </a>
      <a className="block pr-2" href="/contact">
        Contact
      </a>
    </>
  );
}

export default function Nav() {
  const [showMenu, setShowMenu] = useState<boolean>(false);
  return (
    <nav>
      <div className="hidden sm:flex">
        <Links />
      </div>
      <div className="sm:hidden relative">
        <div className="text-white">
          <button className="btn-icon" onClick={() => setShowMenu(!showMenu)}>
            <MenuIcon />
          </button>
        </div>
        {showMenu && (
          <div className="absolute top-10 right-0 z-50 bg-black shadow-xl rounded p-2">
            <Links />
          </div>
        )}
      </div>
    </nav>
  );
}

The most import part of this component is using the breakpoints sm:flex and sm:hidden. On screens where it hits the sm breakpoint it will show the flex div, and hide the hamburger menu. When it hits below the sm breakpoint it will show it.

Conclusion

This is our basic header for now. You can customize the logo, search and nav links to your liking. In the next article we will create a cover page.

Links

https://tailwindcss.com/docs/breakpoints


H
andrewgbliss
17 days ago