如何在AppBar的flex容器中居中对齐按钮及内部内容?
Hey there! Let's get those buttons and your logo centered inside their respective topMenuBoxes divs. The issue right now is that while your divs are taking equal space in the Toolbar (thanks to flex: 1), their internal content isn't being aligned centrally—we just need to add a few flexbox properties to fix that.
Step 1: Update your makeStyles configuration
Modify the topMenuBoxes class to enable flexbox layout for its children, then add alignment rules:
const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, }, logoSize: { marginTop: '30px', height: '70px', }, menuButton: { [theme.breakpoints.up('md')]: { display: 'none', }, marginRight: theme.spacing(2), }, menuText: { [theme.breakpoints.down('sm')]: { display: "none", }, textTransform: 'none', }, topMenuBoxes: { flex: 1, // Add these three lines to center content display: 'flex', justifyContent: 'center', alignItems: 'center', }, }));
What these changes do:
display: flex: Turns thetopMenuBoxesdiv into a flex container, so we can use flexbox alignment on its children.justifyContent: center: Horizontally centers all content inside the div (this is what will make your buttons and logo sit in the middle of their respective sections).alignItems: center: Vertically centers the content, which ensures consistency if you have elements of different heights (like your logo and the text buttons).
Optional: Clean up vertical alignment
If you want all sections to line up perfectly vertically, consider removing the marginTop: '30px' from the logoSize class. The alignItems: center property will handle vertical positioning for the logo automatically, making your AppBar look more polished.
Your existing AppBar JSX doesn't need any changes—just updating the styles will apply the centering.
内容的提问来源于stack exchange,提问作者Anders

