Chatra
Chatra

Reputation: 3139

Scrollable router outlet in Angular

My page is pretty simple. I want a fixed header and footer regardless of the screen size, and want only the content to be scrolled if it is more(if the content overflows).

<div class="header">
 <h2>Title</h2>
</div>
<div class="content">
  <router-outlet></router-outlet>
</div>
<div class="footer">
  <h2>footer</h2>
</div>

I am trying something like this and the exact below code is not working.

Fixed header, footer with scrollable content

Upvotes: 6

Views: 6076

Answers (2)

Javier Rojano
Javier Rojano

Reputation: 982

You can use the Flexbox Layout (Flexible Box) module to align and distribute space among header, content and footer.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

<div class="container">
  <div class="header">
  <nav>
    <a routerLink="/home" routerLinkActive="active">Home</a>
    <a routerLink="/about" routerLinkActive="active">About</a>
  </nav>
  </div>
  <div class="content">
    <router-outlet></router-outlet>
  </div>
  <div class="footer">
    <h2>footer</h2>
  </div>
</div>

we are using an outer element with class=container to apply the display:flex and flex-direction: column properties.

In our CSS we are going to use flex-shrink and flex-grow to distribute the inner elements.

flex-shrink Defines how much a flexbox item should shrink if there's not enough space available.

flex-grow Defines how much a flexbox item should grow if there's space available.

.container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header{
  flex-shrink: 0;
  flex-grow: 0;
}
.content{
  flex-shrink: 1;
  flex-grow: 1;
}

.footer{
  flex-shrink: 0;
  flex-grow: 0;
}

Finally it is important to set height 100% to HTML, body and container elements

html, body{
 height: 100%;
 padding: 0;
 margin: 0;
}

StackBlitz example with angular and flexbox:

https://stackblitz.com/edit/angular-fixed-footer-header

Upvotes: 6

Nils K&#228;hler
Nils K&#228;hler

Reputation: 3001

Have you considered using flexbox do the holy grail ordering of your content between your header and footer.

html,
body,
.page {
  margin: 0;
  height: 100%;
}

.page {
  display: flex;
  flex-direction: column;
}

.header {
  background: tomato;
  flex: 0 0 auto;
}

.footer {
  background: lightgreen;
  flex: 0 0 auto;
}

.content {
  background: lightskyblue;
  flex: 1 1 auto;
  position: relative;
  overflow-y: auto;
}
<div class="page">
  <div class="header">
    <h2>Title</h2>
  </div>
  <div class="content">
    <router-outlet></router-outlet>
    lorem ipsum 
    <br /><br /><br /><br /><br /><br /><br /><br /> ||<br /> ||<br />v<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> much contendo
   
  </div>
  <div class="footer">
    <h2>footer</h2>
  </div>
</div>

Upvotes: 1

Related Questions