Search code examples
csscss-position

Dashboard layout with fixed sidebar and top bar in css


I am creating a dashboard app which has a Side Bar where users can perform some actions and a Top Bar where they can log in log out etc. I am trying to achieve the following 2 layouts:

         

Both the Side Bar and the Top Bar should be fixed vs the content should be scrollable

How can I achieve this?


Solution

  • The HTML is the same:

    <div class='container'>
      <div class="sidebar">Sidebar</div>
      <div class="topbar">Topbar</div>
      <div class="scrollable-content"><h1>Scrollable content</h1>
        Lots of text
      </div>
    </div>
    

    The css for the LHS (where the side bar extends to the top of the screen):

    body {
      margin:0;
      box-sizing: border-box;
      background-color:darkblue;
    }
    .container {
      --topbar-height:50px;
      --sidebar-width:100px;
      color:white;
    }
    .sidebar {
      position:fixed;
      top: 0;
      width: var(--sidebar-width);
      height:100vh;
      background-color: darkgreen;
    }
    .topbar {
      position:fixed;
      top:0;
      width:100%;
      height: var(--topbar-height);
      margin-left: var(--sidebar-width);
      background-color:magenta;
    }
    .scrollable-content {
      margin-top: var(--topbar-height);
      margin-left: var(--sidebar-width);
      background-color:darkblue;
    }
    

    For the 2nd solution (the topbar extends the full width)

    body {
      margin:0;
      box-sizing: border-box;
      background-color:darkblue;
    }
    .container {
      --topbar-height:50px;
      --sidebar-width:100px;
      color:white;
    }
    .sidebar {
      position:fixed;
      top: var(--topbar-height);
      width: var(--sidebar-width);
      height: calc(100vh - var(--topbar-height));
      background-color: darkgreen;
    }
    .topbar {
      position:fixed;
      top:0;
      width:100%;
      height: var(--topbar-height);
      background-color:magenta;
    }
    .scrollable-content {
      margin-top: var(--topbar-height);
      margin-left: var(--sidebar-width);
      background-color:darkblue;
    }
    

    Hope this helps