November 22, 2017
Angular Full Height App Component
Since I have seen a lot of very different approaches to build up an Angular application correctly regarding the CSS positioning, I would like to talk about the different solutions in a short article. Basically it has to be said that our application is usually included in an HTML document as app-root. An index.html
created with the Angular CLI looks like this:
1 2 3 4 5 6 7 8 9 10 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <!-- ... -- </head> <body> <app-root></app-root> </body> </html> |
The app-root
element refers to our AppComponent
. Here we can also remind ourselves that Angular components are not a block elements (display:block;
) by default. This can cause behavior that we do not expect. Usually the AppComponent
should take the full height of the page so that we can place elements like the footer or the header. For use cases where we want to implement a sticky footer within of Angular we are even required to do so.
I’ve seen many approaches that work with Flexbox so far. For example, the body of the page is set to 100vh and converted to a column using Flexbox. The app component is then provided with the information flex-growth to adjust the height. In addition, align-items ensure that the component also takes up the entire width.
Pretty complicated, isn’t it? What bothers me most is the global styles. Although i love Flexbox not everyone in my team is used to work with it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/* NEEDS TO BE GLOBAL STYLES */ body { padding: 0; margin: 0; display: flex; flex-direction: column; align-content: stretch; align-items: stretch; height: 100vh; } app-root { order: 0; flex: 1 1 auto; align-self: auto; display: block; background: red; } |
See a the code in action (html dummy) on codepen.io
Better, simpler Solution
I think we can better. By better I mean less code, no fancy stuff like vh or flexbox. And especially no global styles. Just add this to your AppComponent stylesheet.
1 2 3 4 5 6 7 8 9 10 11 12 |
/** In the Codepen example the selector 'root-app' is used instead since it is not a real Angular application but just HTML markup */ :host { position: absolute; left: 0; right: 0; bottom: 0; top: 0; } |
Based on this, we can now implement a sticky footer as shown here.
Dont nots working in my project with angular 5
Hello Marcio,
Can you provide a Stackblitz as reproduction?
https://stackblitz.com/fork/angular