Issue with Material UI React: Navbar does not properly align the box to the right side

https://i.sstatic.net/CHSwp.png I'm facing an issue with my navbar that is supposed to align all the page options to the right. Despite using a flexbox layout and trying different alignment properties like alignSelf: end, the text only moves slightly downwards instead of aligning properly.

The toolbar orientation is set to row, not column, so I'm unsure why this misalignment is happening.

I attempted to remove the options displayed when the screen resizes, but that didn't resolve the issue either.

Below is the snippet of code causing the problem, and I've marked the section labeled ISSUE:

          {/* Issue */}
      {/* ABOUT, PROJECTS, CONTACT - full screen */}
      <Box sx={{ display: { xs: 'none', md: 'flex' },  alignItems: "flex-end" }}>
        {pages.map((page) => (
          <Button
            key={page}
            onClick={handleCloseNavMenu}
            sx={{ my: 2, color: 'black', display: 'block' }}
          >
            {page}
          </Button>
        ))}
      </Box>

Here's the complete code snippet for reference:

import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Menu from '@mui/material/Menu';
import MenuIcon from '@mui/icons-material/Menu';
import Container from '@mui/material/Container';
import Button from '@mui/material/Button';
import MenuItem from '@mui/material/MenuItem';

const pages = ['About', 'Projects', 'Contact'];

const NavBar = () => {
  const [anchorElNav, setAnchorElNav] = React.useState(null);

  const handleOpenNavMenu = (event) => {
    setAnchorElNav(event.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setAnchorElNav(null);
  };

  return (
    <AppBar position="static" sx={{backgroundColor: "blue"}}>
      <Container maxWidth="xl">
        <Toolbar disableGutters sx={{display: { xs: 'flex' }, flexDirection: "row", backgroundColor: "blue"}}>

          {/* LOGO */}
          <Typography
            variant="h2"
            noWrap
            component="div"
            color="black"
            sx={{ mr: 2, display: { xs: 'none', md: 'flex' } }}
          >
            name
          </Typography>

          {/*Drawer - small screen  */}
          <Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none'} }}>

            {/* Menu triple bar */}
            <IconButton
              size="large"
              aria-label="account of current user"
              aria-controls="menu-appbar"
              aria-haspopup="true"
              onClick={handleOpenNavMenu}
              color="inherit"
            >
              <MenuIcon />
            </IconButton>

            {/* ABOUT, PROJECTS, CONTACT - small screen */}
            <Menu
              id="menu-appbar"
              anchorEl={anchorElNav}
              anchorOrigin={{
                vertical: 'bottom',
                horizontal: 'left',
              }}
              keepMounted
              transformOrigin={{
                vertical: 'top',
                horizontal: 'left',
              }}
              open={Boolean(anchorElNav)}
              onClose={handleCloseNavMenu}
              sx={{
                display: { xs: 'block', md: 'none' },
              }}
            >
              {pages.map((page) => (
                <MenuItem key={page} onClick={handleCloseNavMenu}>
                  <Typography textAlign="center">{page}</Typography>
                </MenuItem>
              ))}
            </Menu>
          </Box>

          {/* LOGO - small screen */}
          <Typography
            variant="h6"
            noWrap
            component="div"
            color="black"
            sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }}
          >
            name
          </Typography>

          {/* Issue */}
          {/* ABOUT, PROJECTS, CONTACT - full screen */}
          <Box sx={{ display: { xs: 'none', md: 'flex' },  alignItems: "flex-end" }}>
            {pages.map((page) => (
              <Button
                key={page}
                onClick={handleCloseNavMenu}
                sx={{ my: 2, color: 'black', display: 'block' }}
              >
                {page}
              </Button>
            ))}
          </Box>

        </Toolbar>
      </Container>
    </AppBar>
  );
};
export default NavBar;

Answer №1

  1. To properly position content in a flexbox layout, use justifyContent or justifySelf for the main axis and alignContent or alignSelf for the cross axis. Make sure to match the CSS properties with the correct axis orientation (row in this case). For more detailed information on flexbox axes, check out this resource
  2. Let me simplify this explanation for you.
  3. The solution is quite simple. In the parent Container, there are two children - "Logo/Typography" and "Box". If you want the "Box" child to move to the end of the container, just apply the justifyContent: space-between property to the parent (Toolbar) to ensure both children are placed at opposite ends.

Feel free to experiment with the code here

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

<AppBar position="static" sx={{ backgroundColor: "blue" }}>
      <Container maxWidth="xl">
        <Toolbar
          disableGutters
          sx={{
            display: { xs: "flex" },
            flexDirection: "row",
            backgroundColor: "blue",
            justifyContent: "space-between"
          }}
        >
          {/* LOGO */}
          <Typography
            variant="h2"
            noWrap
            component="div"
            color="black"
            sx={{ mr: 2, display: { xs: "none", md: "flex" } }}
          >
            name
          </Typography>

          {/*Drawer - small screen  */}
          <Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
            {/* Menu triple bar */}
            <IconButton
              size="large"
              aria-label="account of current user"
              aria-controls="menu-appbar"
              aria-haspopup="true"
              onClick={handleOpenNavMenu}
              color="inherit"
            >
              <MenuIcon />
            </IconButton>

            {/* ABOUT, PROJECTS, CONTACT - small screen */}
            <Menu
              id="menu-appbar"
              anchorEl={anchorElNav}
              anchorOrigin={{
                vertical: "bottom",
                horizontal: "left"
              }}
              keepMounted
              transformOrigin={{
                vertical: "top",
                horizontal: "left"
              }}
              open={Boolean(anchorElNav)}
              onClose={handleCloseNavMenu}
              sx={{
                display: { xs: "block", md: "none" }
              }}
            >
              {pages.map((page) => (
                <MenuItem key={page} onClick={handleCloseNavMenu}>
                  <Typography textAlign="center">{page}</Typography>
                </MenuItem>
              ))}
            </Menu>
          </Box>

          {/* LOGO - small screen */}
          <Typography
            variant="h6"
            noWrap
            component="div"
            color="black"
            sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}
          >
            name
          </Typography>

          {/* Issue */}
          {/* ABOUT, PROJECTS, CONTACT - full screen */}
          <Box
            sx={{
              display: { xs: "none", md: "flex" }
            }}
          >
            {pages.map((page) => (
              <Button
                key={page}
                onClick={handleCloseNavMenu}
                sx={{ my: 2, color: "black", display: "block" }}
              >
                {page}
              </Button>
            ))}
          </Box>
        </Toolbar>
      </Container>
    </AppBar>

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

Changing the CSS background in React when updates occur

Currently working on toggling the CSS background image within this React application. The images have been successfully imported and a variable called "image" is set to the imported image as the iteration increases/decreases with each click. The issue I&a ...

Verify the HTML embed code with either PHP, JavaScript, or the Zend PHP framework

I have a quick question: Are there any effective methods for validating an HTML embed code? I am currently using Zend Framework and prototype+scriptaculous and would appreciate any hints or tips related to this environment. Thank you! ^^ ...

Is there a way to make the X-editable datepicker appear next to the date field rather than in the same spot every time?

When utilizing X-editable, I encountered a problem where specifying the datepicker field mode as "popup" results in the popup displaying correctly. However, when dealing with a long table (either vertically or horizontally), the position of the date/dateti ...

ReactJS implementation for selecting names from a dropdown menu

Hello, I am new to using React. I have a dropdown form with a search engine in it that is working perfectly as I need. The only issue is that when I type, for example, AR in the Symbol field, it shows me ARDRBTC as expected, but I am unable to click on it ...

The background image in CSS fails to display when a relative path is utilized

Currently, I am working on a JavaFX project which has the following file structure (CEP serves as the root directory): CEP +img menu.jpg +src +css_files MainMenu.css The main objective is to set the background image from the img dir ...

Tips for sending props to MUI styled menu for creating specific conditional styling effects

Is it possible to pass props to an already styled Material-UI menu with conditional styling for different minimum widths? The issue I am facing is that the menu's styles are outside of the component receiving the props, so how can I achieve this? c ...

Tips for safeguarding user input data in the event of a Jeditable ajax post failure

Seeking a solution with Jeditable for retaining textarea data and keeping the form visible in case of failed ajax post due to issues like network problem or server error. Is there a way to achieve this with Jeditable? Thanks! ...

When a selection is made in React MUI Virtualized Autocomplete, the autocomplete menu scrolls back to the top

I am currently using reactMUI autocomplete with virtualization because the listbox is expected to contain thousands of items. The virtualization feature works fine, but when I add an onchange function, the listbox automatically scrolls back to the top wh ...

Eliminating the need for the horizontal scroll bar on the webpage

I'm dealing with a page that has multiple controls. Initially, there is no horizontal scrollbar on the page. However, as soon as I introduce an AjaxControlToolkit.Editor or a treeview onto the page, a horizontal scroll bar mysteriously appears. For ...

Problem encountered when attempting to insert a new division into an existing flexbox container

I'm in the process of designing a basic login page using HTML/CSS. To center the box on the screen, I opted for a flexbox layout. So far, I have successfully positioned the Username/password fields and login button just the way I want them. The only t ...

Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page: The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "de ...

Truncating long text labels in Material UI Autocomplete using ReactJS

I am currently utilizing the material UI autocomplete feature and I have a specific requirement to trim the label when it is too lengthy. <Autocomplete id="combo-box-demo" options={top100Films} getOptionLabel={(option) =& ...

Angular's Spanning Powers

How can I make a button call different methods when "Select" or "Change" is clicked? <button type="button" class="btn btn-default" *ngIf="!edit" class="btn btn-default"> <span *ngIf="isNullOrUndefined(class?.classForeignId)">Select</spa ...

JavaScript Tutorial: Extracting the text content of a drop event

Curious about extracting the text value from a drop event, I set out to find an answer. To my surprise, I discovered that it's not as straightforward as I thought. Check out the demo below: <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Where is the best location to store the image files?

I am currently working on a web application that focuses on Image processing, however I have encountered a basic issue. The images are not loading during the runtime of my HTML page. I have tried placing the image files in the src folder, but it seems li ...

The AngularJS page on my website is currently stuck in the mobile version, and strangely, the Google Chrome console is

When browsing our AngularJS website in mobile view on Google Chrome, it gets stuck and becomes unresponsive. The developer console does not show any error messages during this time. To replicate the issue, switch to mobile view, click on the "All top compa ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...

Revamp Material UI Expansion Panel Summary

expansionPanelSummary: { content: { "& > :last-child": { paddingRight: 0 } }, expandIcon: { top: "80%" } } I'm attempting to customize the styles of Materi ...

Ensure the form is properly validated before initiating the submission process on 2checkout

Attempting to prevent the form from being submitted, I implemented the code below. Typically, this method works perfectly fine. However, when integrating 2checkout js (), it does not function as intended. <form onSubmit="validate(); return false;" meth ...

Utilize Ajax datatable to showcase information with the help of CodeIgniter

I am trying to fetch data from a database in my view using ajax, but I am getting the following error message: DataTables warning: table id=users - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please ...