Leviathan
Leviathan

Reputation: 656

Material UI. 2 items inside a grid; one left-aligned, one right-aligned. In the same line

I am having a hard time understanding how to properly use Material UI's flexbox integeration:

This way I can align the items the way I want:

export default function Home() {
    return (
        <Grid container justify={"space-between"}>
            <Grid item>
                <Typography>Left text</Typography>
            </Grid>
            <Grid item>
                <Typography>Right text</Typography>
            </Grid>
        </Grid>
    );
}

But I'd expect that this should work, too:

export default function Home() {
    return (
        <Grid container>
            <Grid item xs={6} justify={"flex-start"}>
                <Typography>Left text</Typography>
            </Grid>
            <Grid item xs={6} justify={"flex-end"}>
                <Typography>Right text</Typography>
            </Grid>
        </Grid>
    );
}

But the latter has not the desired outcome. What am I missing here?

Upvotes: 1

Views: 1975

Answers (1)

IOOIIIO
IOOIIIO

Reputation: 599

Without defining Typography component type, it'll spawn <p> tag, which is of block type. You can find it in the docs: https://material-ui.com/api/typography/ Therefore, you did align something right, but that "something" takes whole 6 columns. Text is not aligned, its heading tag is.

You should try this on "Right text" Typography component:

<Typography align="right">Righttext</Typography>

EDIT: You can also add container prop to Grid component. This way, justify property will be available to you:

<Grid item container xs={6} justify={"flex-end"}>
    <Typography>Right text</Typography>
</Grid>

When you add container prop to Grid component, children of that component become flex elements. Then you don't have to know which tags each Material component spawns when component is rendered.

You can check this behavior in this example of Material docs: https://material-ui.com/components/grid/#nested-grid

Upvotes: 1

Related Questions