arthurakay
arthurakay

Reputation: 5651

React material-ui: centering items on Toolbar

I am trying to implement a toolbar on a page in which I have three ToolbarGroup components:

            <Toolbar>
                <ToolbarGroup firstChild={true} float="left">
                    {prevButton}
                </ToolbarGroup>

                <ToolbarGroup>
                    {releaseBtn}
                </ToolbarGroup>

                <ToolbarGroup lastChild={true} float="right">
                    {nextButton}
                </ToolbarGroup>
            </Toolbar>

The general idea is that prevButton should render all the way to the left of the toolbar (it does), nextButton should render all the way to the right (it does)... and that releaseBtn should be centered on the toolbar (not currently happening).

Per the material-ui docs there doesn't appear to be some easy setting for centered={true}-- how can I accomplish this?

I've tried manually setting the style on the middle ToolbarGroup to margin: 0px auto but that doesn't seem to help.

Upvotes: 5

Views: 15614

Answers (3)

chuckieDub
chuckieDub

Reputation: 1835

In new versions of Material UI you can just use the sx prop:

https://mui.com/system/the-sx-prop/#main-content

<Toolbar sx={{ justifyContent: "space-between" }}> // or "center" for a single element
...
</Toolbar>

Upvotes: 2

Zdenek F
Zdenek F

Reputation: 1899

If anyone runs into this in 2021 or later like I did, material-ui's Toolbar uses Flexbox under the hood, so all you have to do is apply a custom class (or override the default one in the theme):

.myToolbar {
  justify-content: space-between;
}

space-between will distribute the children alongside the main horizontal axis: enter image description here (picture from https://css-tricks.com/snippets/css/a-guide-to-flexbox/)

Upvotes: 6

arthurakay
arthurakay

Reputation: 5651

The final solution for me was to do this:

            <Toolbar>
                <ToolbarGroup firstChild={true} float="left">
                    {prevButton}
                </ToolbarGroup>

                <ToolbarGroup style={{ 
                    float       : 'none', 
                    width       : '200px',
                    marginLeft  : 'auto',
                    marginRight : 'auto'
                }}>
                    {releaseBtn}
                </ToolbarGroup>

                <ToolbarGroup lastChild={true} float="right">
                    {nextButton}
                </ToolbarGroup>
            </Toolbar>

I first had to set the middle ToolbarGroup with no float (not an option through the material-ui props) and then play with the width/margins. I imagine your mileage may vary depending on what you shove inside the ToolbarGroup.

Upvotes: 4

Related Questions