[英]Creating a Toolbar with both Left and Right Justified Elements with Material UI and React.js
我正在嘗試更新我正在創建的網站上的工具欄,我正在努力創建一個工具欄,將內容放置在我想要的位置。 我希望站點的名稱和徽標位於工具欄的左側,而登錄/注冊按鈕則固定在右側。 到目前為止,我已經成功地在我想要的位置獲得了徽標和標題,但是每次我嘗試添加對齊右邊距的按鈕時,它們只是放置在標題/徽標末尾的旁邊。 這是我的代碼:
function Header() {
return (
<ThemeProvider theme={theme}>
<AppBar position="static">
<Toolbar>
<MenuItem edge="start">
<Link to="/" style={{textDecoration:"none", color:"black"}}>
<Typography variant="h3">
<strong>Test</strong>Value
<img style={{width: 60, height: 'auto', verticalAlign: 'middle'}} src='/png/SQUID.png' alt="Squiddy :)"/>
</Typography>
</Link>
</MenuItem>
<MenuItem>
<Link to={"/"} style={{ textDecoration: 'none' }}>
<Button type="button" variant="outlined" color="secondary" float="right">Log-in</Button>
</Link>
<Link to={"/"} style={{ textDecoration: 'none' }}>
<Button type="button" variant="contained" color="secondary" float="right">Register</Button>
</Link>
</MenuItem>
</Toolbar>
</AppBar>
</ThemeProvider>
);
}
我已經嘗試按照 material-ui 文檔中的示例使用flexGrow
,我已經考慮使用grid
元素,但我實際上不想擔心標題和按鈕之間的間距,我只是希望能夠為了將元素對齊到左邊距和右邊距以使它們的位置保持一致而不管它們在什么屏幕上觀看,它們相對於每個邊距都保持在相同的位置。
任何幫助將不勝感激。
function Header() {
return (
<ThemeProvider theme={theme}>
<AppBar position="static">
<Toolbar style={{display:"flex", justifyContent:"space-between"}}>
<div>
<MenuItem edge="start">
<Link to="/" style={{textDecoration:"none", color:"black"}}>
<Typography variant="h3">
<strong>Test</strong>Value
<img style={{width: 60, height: 'auto', verticalAlign: 'middle'}} src='/png/SQUID.png' alt="Squiddy :)"/>
</Typography>
</Link>
</MenuItem>
</div>
<div>
<MenuItem>
<Link to={"/"} style={{ textDecoration: 'none' }}>
<Button type="button" variant="outlined" color="secondary" float="right">Log-in</Button>
</Link>
<Link to={"/"} style={{ textDecoration: 'none' }}>
<Button type="button" variant="contained" color="secondary" float="right">Register</Button>
</Link>
</MenuItem>
</div>
</Toolbar>
</AppBar>
</ThemeProvider>
);
}
將兩個組(左側的事物和右側的事物)都包裝到 div 中。
添加到它們的包含元素(即工具欄):
display:flex;
justify-content:space-between;
align-items:center; // if you want to center both divs vertically, if they're of different height
display:flex;
align-items: center //vertical center
此外,請確保工具欄跨越其整個預期寬度,但我認為這是 MaterialUI 工具欄的默認行為。
如果您希望右側組中的按鈕有一些間距,應用填充是最簡單的解決方案。 您可以對每個元素單獨應用填充(我不知道您是否只有按鈕)以獲得一些細粒度的控制。
或者,如果您希望在右側的所有元素之間創建相等的空間:
.right-div > * + * {
padding-left: 20px;
padding-top: 20px; // use this one if you're stacking your buttons vertically
}
上面的所有元素都排除在右側組中的第一個元素之外,並對其應用左側填充,因此創建的唯一間距是元素之間。 當然,您仍然可以稍后覆蓋特定元素的填充。
請記住,您必須以某種方式應用這些樣式,在那里我假設您會向正確的 div 添加一個“right-div”類。
如果您使用 MUI 的樣式解決方案而不是純 css,它看起來像:
makeStyles({
rightDiv:{
"& > * + *":{
paddingLeft:"20px"
}
}
})
使用styled-components
:
const RightDiv = styled.div`
& > * + * {
paddingLeft:"20px"
}
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.