Material UI Toolbar遵循minWidth要求实现导航栏元素居中方案咨询
解决方案
核心修改点
- 调整
Toolbar的flex布局规则,将三个功能区域(logo区、搜索区、菜单图标区)按固定+自适应+固定的比例分配宽度 - 给搜索组件增加
minWidth限制保证最小宽度,同时设置maxWidth避免宽屏下搜索栏过长 - 调整输入框宽度为100%,让输入内容区域可以占满搜索容器的可用宽度
- 左右两侧固定区域设置为不伸缩,保证logo和菜单图标始终保持原有尺寸且垂直居中
修改后完整代码
import { alpha, styled } from '@mui/material/styles'; import Box from '@mui/material/Box'; import AppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import InputBase from '@mui/material/InputBase'; import SearchIcon from '@mui/icons-material/Search'; import MenuIcon from '@mui/icons-material/Menu'; import IconButton from '@mui/material/IconButton'; import Stack from '@mui/material/Stack'; // 替换为你的logo实际路径 import logo from './logo.png'; const Search = styled('div')(({ theme }) => ({ position: 'relative', borderRadius: 30, backgroundColor: alpha(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.25), }, // 新增宽屏/窄屏宽度限制 minWidth: 280, maxWidth: 600, marginLeft: theme.spacing(2), marginRight: theme.spacing(2), width: '100%', })); const SearchIconWrapper = styled('div')(({ theme }) => ({ padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', })); const StyledInputBase = styled(InputBase)(({ theme }) => ({ color: 'inherit', width: '100%', '& .MuiInputBase-input': { padding: theme.spacing(1, 1, 1, 0), paddingLeft: `calc(1em + ${theme.spacing(4)})`, transition: theme.transitions.create('width'), // 修改为100%宽度占满容器 width: '100%', }, })); export default function SearchAppBar({ search, setSearch }) { return ( <Box sx={{ flexGrow: 1 }}> <AppBar position="fixed" sx={{ backgroundColor: "#55597d" }}> {/* 调整Toolbar配置保证垂直居中 */} <Toolbar sx={{ alignItems: 'center' }}> {/* 左侧logo区:固定宽度不伸缩 */} <Stack direction="row" alignItems="center" sx={{ flex: '0 0 auto' }} > <img style={{ marginRight: "10px" }} src={logo} alt="logo" className="logotext" width="38" height="38" /> </Stack> {/* 中间搜索区:自适应占满剩余空间,自动居中 */} <Search sx={{ flex: '1 1 auto', display: 'flex', justifyContent: 'center' }}> <SearchIconWrapper> <SearchIcon /> </SearchIconWrapper> <StyledInputBase value={search} onChange={(e) => { setSearch(e.target.value); }} placeholder="Search All Games…" inputProps={{ "aria-label": "search" }} /> </Search> {/* 右侧菜单区:固定宽度不伸缩,内容右对齐 */} <Box sx={{ flex: '0 0 auto', display: 'flex', justifyContent: 'flex-end' }}> <IconButton size="large" edge="end" color="inherit" aria-label="open drawer" > <MenuIcon /> </IconButton> </Box> </Toolbar> </AppBar> </Box> ); }
效果说明
- 三个元素全程垂直居中对齐
- 搜索栏在小屏幕下不会小于设置的
minWidth,宽屏下不会超过maxWidth,始终保持居中 - 左右两侧的logo和菜单图标固定位置,不会随屏幕宽度变化发生位移
内容的提问来源于stack exchange,提问作者Forged
相关产品推荐
相关产品推荐

