Left-align or right-align elements in buttons in MUI v5
javascript
mui
投稿日: 2024/06/20
更新日: 2024/07/02
This article is a translation of the following article.
Suppose there is code like the following.
<Stack alignItems="stretch" spacing={1} sx={{ p: 1 }}> <Button href="/articles/new" color="inherit" variant="text" size="large" > <ArticleRoundedIcon sx={{ color: nohColors.mauve, }} /> 記事を投稿する </Button> <Button href="/articles/new?type=miniBlog" color="inherit" variant="text" size="large" sx={{ textTransform: "none" }} > <ArticleRoundedIcon sx={{ color: nohColors.lightBlue }} /> {"記事を投稿する(mini blog)"} </Button> <Button href="/question_posts/new" color="inherit" variant="text" size="large" > <QuestionAnswerRoundedIcon sx={{ color: nohColors.pink }} /> AIに質問する </Button> </Stack>
It is difficult to see if the text is aligned in the center.
In this case, you would like to keep the width of the button element as it is and align the text to the left.
You can make it look clean by adding a <Stack>
component with direction="row"
and width: "100%"
as follows:
<Stack alignItems="stretch" spacing={1} sx={{ p: 1 }}> <Button href="/articles/new" color="inherit" variant="text" size="large" > <Stack direction="row" sx={{ width: "100%" }}> <ArticleRoundedIcon sx={{ color: nohColors.mauve, }} /> 記事を投稿する </Stack> </Button> <Button href="/articles/new?type=miniBlog" color="inherit" variant="text" size="large" sx={{ textTransform: "none" }} > <Stack direction="row" sx={{ width: "100%" }}> <ArticleRoundedIcon sx={{ color: nohColors.lightBlue }} /> {"記事を投稿する(mini blog)"} </Stack> </Button> <Button href="/question_posts/new" color="inherit" variant="text" size="large" > <Stack direction="row" sx={{ width: "100%" }}> <QuestionAnswerRoundedIcon sx={{ color: nohColors.pink }} /> AIに質問する </Stack> </Button> </Stack>
If you want to align to the right, use justifyContent="flex-end"
property in the Stack component.
<Stack alignItems="stretch" spacing={1} sx={{ p: 1 }}> <Button href="/articles/new" color="inherit" variant="text" size="large" > <Stack direction="row" justifyContent="flex-end" sx={{ width: "100%" }} > <ArticleRoundedIcon sx={{ color: nohColors.mauve, }} /> 記事を投稿する </Stack> </Button> <Button href="/articles/new?type=miniBlog" color="inherit" variant="text" size="large" sx={{ textTransform: "none" }} > <Stack direction="row" justifyContent="flex-end" sx={{ width: "100%" }} > <ArticleRoundedIcon sx={{ color: nohColors.lightBlue }} /> {"記事を投稿する(mini blog)"} </Stack> </Button> <Button href="/question_posts/new" color="inherit" variant="text" size="large" > <Stack direction="row" justifyContent="flex-end" sx={{ width: "100%" }} > <QuestionAnswerRoundedIcon sx={{ color: nohColors.pink }} /> AIに質問する </Stack> </Button> </Stack>
Table of Contents