Search code examples
htmlcsspositionfooterabsolute

Push footer to the bottom of the page


The site structure is as follows - there is a common unit (content), which houses all of the elements of the site and the second unit, a footer which is to be pressed against the bottom of the site.

Content block is position: absolute for aligning the center (horizontal) - to decrease the screen when it is uniformly left for right and left its borders. The problem is that with such a block structure the footer doesn't stay pressed against the bottom of the page. Here's the code :

body {
  margin: 0px;
  padding: 0px;
}

.a_wrapper {
  width: 600px;
  left: 50%;
  margin-left: -300px;
  position: absolute;
  border: 1px dotted #000000;
}

.a {
  height: 800px;
}

.b {
  width: 90%;
  height: 50px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  margin: auto;
  position: absolute;
  border: 1px solid #000000;
}
<div class = "a_wrapper">
    <div class = "a"></div>
</div>
<div class = "b">
</div>

https://jsfiddle.net/0k979ud5/


Solution

  • There are two things causing this - because of using only absolutely positioned elements, which takes them out of document flow, the body element itself has no height. So that would need to be set the same as the content. Then the footer is positioned according to the nearest positioned element, also because of position: absolute. It's direct parent is body which has no positioning so it will default to the window object. To solve this, body should be given position: relative :

    body {
      height: 800px;
      position: relative;
      padding: 0px;
      margin: 0px;
    }
    
    .a_wrapper {
      width: 600px;
      left: 50%;
      margin-left: -300px;
      position: absolute;
      border: 1px dotted #000000;
    }
    
    .a {
      height: 800px;
    }
    
    .b {
      width: 90%;
      height: 50px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      margin: auto;
      position: absolute;
      border: 1px solid #000000;
    }
    <div class="a_wrapper">
        <div class="a"></div>
    </div>
    <div class="b"></div>

    It the footer should be below the content, body would have to be 850 pixels high of course...