1

I just found out a solution for creating sticky footers:

html {
    position: relative;
}
#footer {
    position: absolute;
    bottom: 0;
    left: 0; right: 0;
}

Though I am wondering on how advised it is to put position:relative on the html tag.

The way I understand it: instead of position: absolute being relative to the viewport, it becomes relative to the document.

Is this good practice?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Angivare
  • 467
  • 5
  • 16
  • If it works for you, it's a good practice. There is nothing wrong to style `html` elements, it the same as styling other ones. – pavel Feb 16 '15 at 08:01

1 Answers1

3

While the root element html is stylable by CSS just like any other element, certain properties may behave differently by virtue of it being the root element. position is one of those properties: in particular the spec has this to say:

User agents may treat position as 'static' on the root element.

As far as I know, no modern browser actually does this, but it's still not guaranteed that position: relative will always work on the root element. In your case, you can simply avoid this by setting position: relative on the body element instead of the html element:

body {
    position: relative;
}
#footer {
    position: absolute;
    bottom: 0;
    left: 0; right: 0;
}

Note that the footer will not stick to the bottom of the page if the body does not reach the height of the viewport (e.g. when there is not enough content in the page). If this is an issue for you, set height and min-height on html and body following the instructions in my answer here:

html {
    height: 100%;
}
body {
    position: relative;
    min-height: 100%;
}
#footer {
    position: absolute;
    bottom: 0;
    left: 0; right: 0;
}
Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Thanks. That's what I needed to know; additionnally, could you acknowledge my thought on that trick making `position: absolute` relative to document instead of viewport? That would help me understanding the thing better. Also, I had put `min-height` already, just forgot to put it in the example. – Angivare Feb 16 '15 at 08:30
  • @Angivare: Your understanding is correct, for as long as the position property isn't forced to be static anyway. – BoltClock Feb 16 '15 at 08:32
  • @Angivare: I rejected your edit because my code does not match the code that you have - notice that I set `min-height` on *`body`*, not `html`. Setting `min-height` on `html` alone has no effect. – BoltClock Feb 16 '15 at 08:37
  • Oh right, that's important enough to point out. Thank you for your answer anyway – Angivare Feb 16 '15 at 08:40