Search code examples
cssreactjsjsxsemantic-ui-react

semantic-ui-react Content goes under the menu when it's stackable


I have a main component

return (
    <>
      <NavBar />
      <Container style={{marginTop: '7em'}}>
        <List>
          {accounts.map(account => (
            <List.Item key={account.id}>
              {account.id}
            </List.Item>
          ))}
        </List>
      </Container>
    </>
  );

That contains a NavBar

import React from 'react';
import { Container, Icon, Menu } from 'semantic-ui-react';

export default function NavBar() {
    return (
        <Menu inverted fixed='top' stackable>
            <Container>
                <Menu.Item header>
                    <Icon name='chess pawn' size='large' />
                    Menu 1
                </Menu.Item>
                <Menu.Item name='Menu 2' />
                <Menu.Item name='Menu 3' />
                <Menu.Item name='Menu 4' />
                <Menu.Item name='Menu 5' />
            </Container>
        </Menu>
    )
}

This looks alright on desktop

enter image description here

but on mobile resolutions when the Menu stacks and some content goes behind it.

enter image description here

Is there any elegant way to address this issue?


Solution

  • In semantic-ui, when using fixed='top' on Menu, it is taken out of the flow of document due to position: fixed, which allows other content to go under it.

    It is also the reason why a higher marginTop was needed on the content container to create some space on top.

    Instead of fixed='top', try use a custom class (or inline style) for NavBar to apply position: sticky on it, so it is placed considering the flow but still stays in view as the window scrolls.

    More about position: sticky

    Live demo of the minimized example: stackblitz

    Example:

    .custom-nav {
      position: sticky;
      top: 0;
    }
    

    Add the className to NavBar:

    import React from 'react';
    import { Container, Icon, Menu } from 'semantic-ui-react';
    
    export default function NavBar() {
        return (
            <Menu inverted stackable className="custom-nav">
                <Container>
                    <Menu.Item header>
                        <Icon name='chess pawn' size='large' />
                        Menu 1
                    </Menu.Item>
                    <Menu.Item name='Menu 2' />
                    <Menu.Item name='Menu 3' />
                    <Menu.Item name='Menu 4' />
                    <Menu.Item name='Menu 5' />
                </Container>
            </Menu>
        )
    }
    

    Alternatively, perhaps a sticky component by semantic-ui can be used to wrap NavBar for the same result, although it seems that it would result in an additional wrapper in the structure.

    Hope this will help.