Tips for aligning a form in the center of a webpage

I have a code snippet using material-ui that I want to center on the page, but it's not working. Can someone please help me fix this issue? Thank you in advance.

 import React from 'react';
 import { makeStyles } from '@material-ui/core/styles';
 import TextField from '@material-ui/core/TextField';
 import Button from '@material-ui/core/Button';

 const useStyles = makeStyles((theme) => ({
  root: {
 '& > *': {
   margin: theme.spacing(1),
   width: '25ch',
   display: 'flex',
   textAlign : 'center'
 },
},
}));

   export default function Login() {
   const classes = useStyles();

return (
 <form className={classes.root} noValidate autoComplete="off">
   <TextField id="outlined-basic-user" label="UserName" variant="outlined"/>
   <TextField id="outlined-basic-pswd" label="Password" variant="outlined" />
   <Button variant="contained" color="primary">
     Provider
   </Button>
   <Button variant="contained" color="primary">
     Patient
   </Button>
 </form>
);
}



Answer №1

Create a wrapper element for the form and set its style to have width: 100% and height: 100vh

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles((theme) => ({
  root: {
    margin: theme.spacing(1),
    width: "300px",
    height: "400px",
    display: "flex",
    flexDirection: "column",
    justifyContent: "space-around",
    textAlign: "center"
  },
  wrapper: {
    width: "100%",
    height: "100vh",
    display: "flex",
    justifyContent: "center",
    alignItems: "center"
  }
}));

export default function App() {
  const classes = useStyles();

  return (
    <div className={classes.wrapper}>
      <form className={classes.root} noValidate autoComplete="off">
        <TextField
          id="outlined-basic-user"
          label="UserName"
          variant="outlined"
        />
        <TextField
          id="outlined-basic-pswd"
          label="Password"
          variant="outlined"
        />
        <Button variant="contained" color="primary">
          Provider
        </Button>
        <Button variant="contained" color="primary">
          Patient
        </Button>
      </form>
    </div>
  );
}

Codesandbox

Answer №2

Utilizing flex on the child elements may not have an effect, as textAlign is more suitable for the wrapper element. Nevertheless, employing flex is considered more advantageous in modern times.

You could consider implementing the following:

 const customStyles = makeStyles((theme) => ({
  container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center' // to ensure vertical centering
  },
}));

Answer №3

To achieve the desired result, simply apply justify-content: center; along with display:flex. If this solution does not work for you, share a live demo on sandbox and I will provide further assistance.

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

Arranging Bootstrap Grids within Laravel

On my current web page, I have implemented Bootstrap Grids as seen in the image below. Check out My Bootstrap Grid Layout However, I am aiming to achieve a grid layout similar to the one shown in the picture with a red indicator. Here is the Desired Boo ...

The Angular Material Table experienced a collapse when trying to render over 20 columns simultaneously

Currently, I am experiencing an issue in Angular Version 5 where the Angular Material Table collapses when rendering more than 20 columns. Here is a snapshot of what my table looks like: https://i.stack.imgur.com/MXfvQ.png https://i.stack.imgur.com/XHWgq ...

Is adjusting a ref's value during render instead of using useEffect a secure practice?

Utilizing the useRef hook, I am storing the most recent value of a prop to access later in an async callback like an onClick handler. Instead of adding 'value' to the useCallback dependencies list, I opted for a ref since I anticipate frequent ch ...

Experiencing an excessive amount of re-renders due to state setting? Consider implementing useSW

I am currently utilizing useSWR to fetch data and then calculating a total using the reduce method. Strangely, when I try to update the state with the calculated value, it triggers multiple re-renders causing the 'Too many re-renders' error messa ...

The cascading style sheet does not have any effect on the layout of the tables within the

I am trying to apply a CSS style to give all tables on my HTML pages a 1px border width. However, for some reason, the borders are not showing up in my HTML files! What could be causing this issue? <!-- <style type="text/css"> --> body{backg ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...

What is the process for choosing and making changes to a specific portion of a textContent?

<h1 id="block ">This is my header block</h1> To dynamically change the color of the "block" word every 2 seconds using JavaScript: let colors = ["blue", "green", "pink", "purple"]; let curColor = 0; const changeColor = () => { ...

Adjusting animation placement when resizing the window

Is it possible to utilize jquery window.resize() to ensure that the positioning of the two donuts never interferes with the text in the middle of the home? I am unsure of how to connect the x and y values of the window size to adjust the top/left and botto ...

The error message "require is not defined in React.js" indicates that the required dependency is

As I delve into React coding, the following lines are a part of my code: var React = require('react'); For setting up React, I referred to tutorialspoint. The installation directory is set to /Desktop/reactApp/. My React code is executed from ...

Tips for Showing a Portion of an Object in React JS

Need help displaying subitems of an object. I can display the main item but struggling with subitems. Here's the attached image for reference: https://i.sstatic.net/WTgb3.png I'm having trouble displaying the comments section in the object. I&a ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

Interacting with JQuery UI Button causes it to shift position on mouseover

In my table, there are two large cells. The left cell contains two drop-downs and a JQuery UI button that is causing trouble, while the right cell displays a list generated from an AJAX database query. As the list grows longer, the button gradually moves u ...

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

The issue with window.addEventListener failing to update state when the scrollY is not at zero persists during route changes

When using addEventListener in the componentDidMount lifecycle method to add a class to a header based on the scroll behavior, an issue arises when changing routes via a modal or browser back button. The scrolling state is not accurately reflected as the s ...

Dealing with full-width elements on mobile devices

I've got a pretty basic question here but can't seem to find a straightforward answer. I'm using Bootstrap to style a website and struggling with making it mobile-responsive. Following the given answer, I used this code to show a button ne ...

Retrieve the child element that is being clicked

Alright, I'm facing a little issue here (it seems simple, but I just can't seem to crack it)... Let me paint the picture with a snippet of HTML code below: <!-- New Website #1 --> <!DOCTYPE html> <html style='min-height:0px; ...

Unresponsive CSS styles on a specific DIV element

Here is the HTML code I am currently working with: <body> <section id="info"> <div class="status"> ... I have been attempting to apply styles to the div with a class of 'status' using my CSS file linke ...

Next.js is complaining that React has identified a rearrangement of Hooks despite being called from the top level

When using SWR to fetch data from my database, I encountered the following error message: Warning: React has detected a change in the order of Hooks called by OrganizationSettings. This will lead to bugs and errors if not fixed. For more information, r ...

Securing third party API keys on Firebase hosting: Best practices and tips

In my ReactJS-Firestore project, I am faced with the challenge of securing different third-party API keys used. While services like Netlify offer features like environment variables for added security, I am struggling to find a similar solution in Firebase ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...