Tips for positioning buttons within a responsive navigation bar

In my code for the navigation bar, located in "Navbar2.jsx", I have included various components and styles to create a dynamic navbar with dropdown functionality. The issue I am facing is that when the menu drops down on mobile view, it shifts the position of the "X" button instead of staying aligned.

'use client';

import Link from 'next/link';
import Image from 'next/image';
import NavItem from './NavItem';
import { motion } from 'framer-motion';
import { navVariants } from '../utils/motion';
import styles from '../styles';
import { useState } from 'react';
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
import { Disclosure, Menu, Transition } from '@headlessui/react';

const menu_list = [
  { name: 'Home', href: '/', current: true },
  { name: 'About', href: '/', current: false },
  { name: 'Contact', href: '/', current: false },
]

function classNames(...classes) {
  return classes.filter(Boolean).join(' ')
}

const Navbar2 = () => {
  const [isOpen, setIsOpen] = useState(false);

  return(
    <motion.nav
      variants={navVariants}
      initial='hidden'
      whileInView='show'
      className={`${styles.xPaddings} py-8 relative z-30`}
    >
      <div className='absolute w-[50%] inset-0 gradient-01' />
      <div className={`${styles.innerWidth} mx-auto flex justify-between gap-8`}>
        <Link href='/' className='z-30 opacity-50 hover:opacity-100'>
          <Image
            src='/headset.svg'
            alt='logo'
            width={30}
            height={30}
            className='object-contain'
          />
        </Link>
        <h2 className='font-extrabold text-[24px] leading-[30px] text-white'>
          TITLE
              </h2>
              <div className='hidden sm:flex space-x-4'>
                {menu_list.map((item) => (
                  <Link href={item.href} className={classNames(
                    item.current ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                    'rounded-md px-3 py-2 text-sm font-medium'
                  )}
                  aria-current={item.current ? 'page' : undefined}
                  >
                    {item.name}
                  </Link>
                ))}
              </div>
            <div>
              <button type='button' onClick={() => setIsOpen(!isOpen)} className='sm:hidden inline-flex items-center justify-center rounded-md p-2 text-gray-400 hover:bg-gray-700 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white'>
                <span className='sr-only'>Open main menu</span>
                {isOpen ? (
                  <XMarkIcon className="block h-6 w-6 " aria-hidden="true" />
                ) : (
                  <Bars3Icon className="block h-6 w-6" aria-hidden="true" />
                )}
              </button>
              {isOpen && (

                <div className='space-y-1 px-2 pb-3 pt-2'>
                  <div className='rounded-md ring-1 ring-black ring-opacity-5 overflow-hidden'>
                    {menu_list.map((item) => (
                      <Link href={item.href} key={item.name} className={classNames(
                            item.current ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                            'block px-4 py-2 text-sm'
                          )}
                          aria-current={item.current ? 'page' : undefined}
                        >
                          {item.name}
                      </Link>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </motion.nav>
      )
    }

export default Navbar2;

The current behavior can be seen in these screenshots: https://i.sstatic.net/85TQ4.png

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

I have attempted adding different CSS attributes like "absolute" and "justify-end" to the button's class, but they did not resolve the issue. The complete project files are available on GitHub here

Answer №1

It is recommended to switch the <button> class from inline-flex to flex, in order to change it to a block layout. Then, add margin-left: auto using the ml-auto class to ensure the <button> is always aligned to the right:

<script src="https://cdn.tailwindcss.com"></script>

<body class="bg-slate-950">
  <nav class="py-8 relative z-30">
    <div class="absolute w-[50%] inset-0 gradient-01"></div>
    <div class="mx-auto flex justify-between gap-8">
      <a href="/" class="z-30 opacity-50 hover:opacity-100">
        <img src="https://picsum.photos/30/30" alt="logo" width="30" height="30" class="object-contain" />
      </a>
      <h2 class="font-extrabold text-[24px] leading-[30px] text-white">
        TITLE
      </h2>
      <div>
        <button type="button" class="flex items-center justify-center rounded-md p-2 text-gray-400 hover:bg-gray-700 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white ml-auto">
          <span class="sr-only">Open main menu</span>
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="block w-6 h-6">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
        <div class="space-y-1 px-2 pb-3 pt-2">
          <div class="rounded-md ring-1 ring-black ring-opacity-5 overflow-hidden">
            <a class="text-gray-300 hover:bg-gray-700 hover:text-white block px-4 py-2 text-sm">
              {item.name}
            </a>
          </div>
        </div>
      </div>
    </div>
  </nav>

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

Error: Unable to load the parser '@typescript-eslint/parser' as specified in the configuration file '.eslintrc.json' for eslint-config-next/core-web-vitals

When starting a new Next.js application with the specific configuration below: ✔ What name do you want to give your project? … app ✔ Do you want to use TypeScript? … No / [Yes] ✔ Do you want to use ESLint? … No / [Yes] ✔ Do you want to use T ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

Setting the default value of a React checkbox to be true

I am dealing with a backend value that initially appears on the UI as false or null. When the value is false or null, I need my checkbox to be checked, and if the backend value is true, then the checkbox should be unchecked. This functionality is implement ...

Having trouble with applying a custom class to React Bootstrap tabs?

When utilizing the react bootstrap tabs component, I encountered an issue with implementing a custom CSS style for the nav-link element within it using a customized parent class indicator. <Tabs defaultActiveKey="signup_renter" i ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Is there a way for me to extract a file from the file system in React Native, convert it to base64, and then post it as JSON using HTTP

After following a helpful guide on audio and video recording in React Native from this informative article, I utilized the code available on Github here. The app I built allows users to record audio and save it to the file system. However, I encountered a ...

Trouble Viewing Image File

I am facing an issue where I cannot upload an image file from my computer onto my HTML file, as it is not showing up in the browser. However, when I link an image file from the web, it works perfectly fine. I have double-checked the file path and ensured ...

Why does the activeClassName of my React Router NavLink for the path '/' persist even after navigating to another page?

My navbar currently consists of three different components/links, laid out in the following structure: <ul className="flex text-white flex-col lg:flex-row list-none lg:ml-auto"> <NavLink activeClassName="active" ...

The value of the Material UI TextField Input Time Picker remains static and cannot be altered

After using this CodeSandbox example for material UI time picker (https://codesandbox.io/s/5154qzmjl), I am facing an issue where I am unable to change the value of the time. In my code, I have mapped the days array in the state to the TextField: this.st ...

I'd like to display just two names from a list at a time and have the option to click on a button to reveal the next two names, unfortunately, there

I am trying to modify my code so that it only displays the first 2 items in an array initially, and then on clicking a button, the next 2 names are displayed until the end. However, the code I have written seems to have a bug. Can you help me correct this ...

What is the best way to implement overflow hidden in an unordered list?

My goal is to achieve the following: - - I am struggling with keeping my unordered list on a single line with overflow:hidden. I want the ul to flow naturally without restructuring the HTML or using absolute positioning for the arrows. Can you help me w ...

The JavaScript Top Slide Down effect is malfunctioning

Every time I press the "More" button, I expect some forms to pop out but nothing happens. Can someone please assist me with this issue? <body> <!--Hero Image--> <div class="hero-image"> <div class="hero ...

What is the best way to display JSON data within a React component?

Is there a way to display JSON data in a react component by rendering each array as a separate unordered list? Here is the JSON Data: "value":{ "h3":[ "Best selling products", "Best Corporat ...

Customizing the select2 plugin in jQuery - A user-friendly alternative for select boxes

I am currently seeking a method to personalize the appearance of the Select2 plugin within a project. Although I have reviewed the documentation, I was unable to locate specific instructions on how to modify the styling of the select box. Please refer to ...

Modify the hue in the tailwind.config.js file to create a custom color

I'm currently developing a VUE application where I need to tailor the primary color in litepie-datepicker to #A7F3D0 (emerald series) within my tailwind.config.js file. https://i.sstatic.net/Tt8E4.png I've attempted these code snippets, but unf ...

When Webpack presets are utilized, class properties undergo a transformation

As I was testing my React project on webpack-dev-server, I encountered an issue with using the classfield syntax. The error occurred during state initialization. client:162 ./src/containers/App.js Module build failed (from ./node_modules/babel-loader/lib/ ...

Switching the background image dynamically in Vue.js upon page access

My goal is to update the 'background-image' when the page is accessed. export default { created () { document.getElementsByTagName('html')[0].style.background = "url('../assets/background-blur.png') center" } } //Logi ...

Tips for effectively placing a page scope block using BEM

Here is the current structure of my header. The page component is assumed to be the root. Currently, the geometry of the social-links block is being controlled by the header__social-links mix (positioned absolutely relative to the header). How can I prop ...

Having difficulty rotating images using the jQuery Rotate plugin?

I have successfully implemented a rotate plugin to rotate my logo on my website. However, I am facing an issue where the content below the rotating image is moving up and down. Could someone please advise me on how to correct this issue? You can view my ...