Home > Blockchain >  Dashboard layout with fixed sidebar and top bar in css
Dashboard layout with fixed sidebar and top bar in css

Time:08-31

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?

CodePudding user response:

You can use the CSS position property to achieve this.

    #sidebar {
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        width: 100px;
    }
    // Width for sidebar and height for topbar will be relative to the content you can change
    #topbar {
        position: fixed;
        top: 0;
        left: 100px;
        height: fit-content;
    }
    // Adjust padding to avoid content being covered by the top and sidebar
    body {
        padding: 100px; 
    }

CodePudding user response:

The HTML is the same:

<div class='container'>
  <div >Sidebar</div>
  <div >Topbar</div>
  <div ><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

  • Related