cssreactjsmaterial-uiappbar

AppBar overlaps with other elements


I am starting to use React/Material-UI, and also new to CSS etc... I have a simple page layout with an APPBar. Unfortunately this AppBar overlaps the elements which are meant to go below it.

I have found this answer: AppBar Material UI questions

But this feels completely wrong. What if my AppBar has a variable height, depending on the icons, display modes etc...?

I have tried to create a vertical grid, to wrap the elements in different items, made the top container a flex one and play with flex settings, nothing seems to work, the app bar always sits on top of the text.

The code is very simple:

import React from 'react';
import { AppBar, Typography, Box } from '@material-ui/core';

function App() {
    return (
        <div>
            <AppBar>
                <Typography variant='h3'>
                    AppBar
                </Typography>
            </AppBar>
            <Box>
                <Typography variant='h1' style={{ border: '1px solid black' }}>
                    Hello
                </Typography>
            </Box>
        </div>
    )
}

export default App;

The "Hello" text chunk is only half visible:

enter image description here


Solution

  • This is happening because the MaterialUI App Bar defaults to position="fixed". This separates it from the standard DOM's layout to allow content to scroll beneath it, but as a result no space is made for it on the page.

    You can get around this by wrapping all content below it in a div and specifying enough margin, or by changing the position property of <AppBar> so it's no longer "fixed". In your example, you could also just apply the styles to <Box> if that's the only content below the <AppBar>.

    e.g.

    import React from 'react';
    import { AppBar, Typography, Box } from '@material-ui/core';
    
    function App() {
        return (
            <div>
                <AppBar>
                    <Typography variant='h3'>
                        AppBar
                    </Typography>
                </AppBar>
                <div style={{marginTop: 80}}>
                    <Box>
                        <Typography variant='h1' style={{ border: '1px solid black' }}>
                            Hello
                        </Typography>
                    </Box>
                </div>
            </div>
        )
    }
    
    export default App;