I trapped in this problem many times so I would like to leave it here.
I wanted this 'Login' button to be on the right edge of this header but I could not apply text-align: right.
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
button:{
textAlign: 'right',
display:'block',
}
}));
export default function Top() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static" color='white'>
<Toolbar >
<Button className={classes.button}
color="inherit">Login
</Button>
</Toolbar>
</AppBar>
</div>
);
}
I found out this does not work because Button is enclosed by the parent element, 'Toolbar'. When you use 'text-align', it needs to know 'where is the center?' or 'where is the middle?'. Therefore, you should select a parent element which is also a block element, and apply text-align.
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
button:{
textAlign: 'right',
display:'block',
}
}));
export default function Top() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static" color='white'>
<Toolbar className={classes.button}>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
I used to use 'float: right' but it's not really recommended for various reasons so I've been trying to find other ways!
Please give me any correction if my grammar is weird or does not make sense!
Top comments (2)
There is many solutions to align the button to the right, without using "float: right".
The easiest is maybe to use flex-box on you classes "button" :
A better solution will be to use
component of Material UI. Check out : codesandbox.io/s/react-material-ui...
Ohhh that is easier! thank you for teaching me :)