How to keep the footer always down

1

I would like to know how to keep the site footer always at the bottom of the site, even if the site content is small, like the example below.

If I put a margin top, it does not stay down there at all resolutions, I tried with percentage and I could not.

    
asked by anonymous 08.09.2015 / 17:55

5 answers

6

You can fix an element at the bottom of the page using position fixed or absolute and set bottom to 0px .

Here is an example with header and footer fixed and section with fixed width and centered on the page.

var showContent = document.getElementById("showContent");
var content = document.getElementById("content");

showContent.addEventListener("click", function (event) {
	content.classList.remove("invisivel");
    showContent.classList.add("invisivel");
});
body, html {
    position: absolute;    
    width: 100%;
    height: 100%;
    padding: 0px;
    margin: 0px;
}

section {
    position: absolute;
    background-color: whitesmoke;
    top: 40px;
    bottom: 40px;
    width: 100%;
    overflow: auto;    
    z-index: 0;
}

section #container {
    position: absolute;
    box-shadow: 0px 0px 10px black;
    background-color: white;
    margin: auto;
    width: 400px;
    min-height: 100%;
    right: 0px;
    left: 0px;
}

header,
footer {
    position: absolute;
    background-color: gainsboro;
    height: 40px;
    width: 100%;
    box-shadow: 0px 0px 10px black;
    z-index: 1;
}

header {
    top: 0px;
}

footer {
    bottom: 0px;
}

.invisivel {
    display: none;
}
<header></header>
<section>
  <div id="container">
    <input id="showContent" type="button" value="Exibir Conteudo" /> 
    <div id="content" class="invisivel">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tincidunt efficitur fermentum. Integer viverra tristique diam eget commodo. Aliquam faucibus velit nec porttitor fermentum. Aliquam tristique tempor sem nec aliquam. Etiam id lorem at tellus iaculis iaculis. Donec tincidunt lectus sed dolor tincidunt efficitur. Cras eu neque ex. Vestibulum eu volutpat lectus. Suspendisse varius, turpis quis aliquam dapibus, ligula ligula facilisis nunc, id tincidunt nulla massa sit amet mauris. Praesent sed ex id neque sagittis egestas laoreet eget purus. Nunc egestas consequat tellus, ut ullamcorper eros facilisis eu. Maecenas a lorem nisi.
      </p>
      <p>
        Cras faucibus velit at lorem laoreet, sed vulputate eros venenatis. Aliquam erat volutpat. Pellentesque enim eros, varius eget cursus ut, euismod quis nisl. Integer volutpat tempus velit. Ut turpis lorem, facilisis a consequat in, tincidunt sit amet felis. Nulla imperdiet leo eget justo consequat, nec luctus odio sodales. Etiam urna est, lobortis in tristique at, tincidunt a ipsum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque tincidunt id ipsum in rutrum. Donec tempor id ligula nec consectetur. Mauris mattis, mi quis consequat tincidunt, turpis quam faucibus risus, ac iaculis nunc sapien quis lorem.
      </p>
      <p>
        Nunc finibus tortor ipsum, quis maximus sapien pharetra vel. Mauris auctor rutrum est, ut fringilla nisi auctor id. Sed lacinia laoreet rutrum. Nulla eget volutpat lacus, ac ullamcorper mi. Aenean consequat vulputate molestie. Ut dictum arcu sit amet elit vehicula posuere. Curabitur gravida, eros vestibulum mollis faucibus, quam tellus laoreet nibh, ut viverra est nulla non lacus. Proin mollis tortor eget orci convallis, et posuere turpis congue. Pellentesque accumsan, lorem non dapibus dapibus, dolor risus aliquam purus, vel vestibulum orci sem non arcu. Etiam accumsan sollicitudin libero. Suspendisse tristique, tortor eu tristique vehicula, lectus nibh tempus orci, eget elementum magna libero non nibh. Mauris dapibus quam nec finibus eleifend. Curabitur ut lacus at velit vulputate fringilla. Duis cursus dictum nulla, porta pellentesque nulla consequat eu. Aenean elementum condimentum metus et pharetra.
      </p>
      <p>
        Fusce varius metus eu nibh porta, sit amet facilisis sapien dapibus. Pellentesque ullamcorper dui leo, vitae tristique massa molestie vitae. Morbi sit amet mauris non eros lobortis vestibulum eu et orci. Quisque in massa at quam malesuada consequat vel vitae augue. Aenean ut purus elementum, malesuada risus sodales, varius neque. Aenean gravida congue diam, id finibus felis vulputate in. Curabitur mattis quis erat at porta. Fusce non congue massa, at convallis justo.
      </p>
      <p>
        Sed pellentesque diam eu nibh finibus, vitae euismod diam blandit. Ut luctus, massa gravida efficitur pretium, eros felis ullamcorper quam, vitae tempor sapien lectus commodo enim. Nunc eget mi eget nibh posuere interdum quis sed nibh. Phasellus iaculis luctus dapibus. Vestibulum at finibus urna, lobortis maximus erat. Donec maximus risus id est tristique rutrum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas blandit, lacus eu semper finibus, elit sapien eleifend justo, in vehicula libero lacus imperdiet elit. Vestibulum lacus odio, luctus eu ex eget, efficitur ultrices est. In eget eleifend ex.
      </p>
    </div>
  </div>
</section>
<footer></footer>
    
08.09.2015 / 18:23
3

For me the most sensible and unambitious way is to use calc, with it you avoid using position absolute or javascript often forcing the reflow and overlap of elements with z-index, not to mention that it avoids various bugs and is supported in almost all browsers, except for some browsers for mobile .. But I do not worry about that, since there is usually scrolling on the vertical axis of the page on the mobile. I use the following code:

main {
    min-height: 100vh;
    min-height: -webkit-calc(100vh - 100px);
    min-height:    -moz-calc(100vh - 100px);
    min-height:         calc(100vh - 100px);
}

//100px é a altura do footer

footer {
    min-height: 100px;
}

Ex:

/*reset*/
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

main {
  background-color: rgb(201, 225, 222);
  display: block;
  min-height: 100vh;
  min-height: -webkit-calc(100vh - 100px);
  min-height: -moz-calc(100vh - 100px);
  min-height: calc(100vh - 100px);
  position: relative;
  width: 100%;
}
footer {
  background-color: rgb(0, 55, 96);
  display: block;
  min-height: 100px;
  width: 100%;
}
<main></main>
<footer></footer>
    
10.09.2015 / 16:06
2

If you want a simpler solution:

html,
body {
  margin:0;
  padding:0;
  height:100%;
}
#wrapper {
  min-height:100%;
  position:relative;
}
#header {
  padding:10px;
  background:#5ee;
}
#content {
  padding:10px;
  padding-bottom:80px;   /* Height of the footer element */
}
#footer {
  width:100%;
  height:80px;
  position:absolute;
  bottom:0;
  left:0;
  background:#ee5;
}
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
    
09.09.2015 / 15:49
1

I created the following solution in Javascript, there might be other ways to do it, but I did so.

Explaining the code:

What I did was the following, so when the page was loaded or resized, I did a function. This function evaluates if the rod is in a higher position than the bottom of the window, if it positions it using the following values for the bottom margin of the content div:

  • Screen size = > window height
  • top.offsetHeight = > height of the top div
  • content.offsetHeight = > height of the content div
  • rodape.offsetHeight = > div div height
  • 20 = > top margin of div content

Otherwise apply only a margin of 20px for the content div.

window.onload = posicionaRodape;
window.onresize = posicionaRodape;

function posicionaRodape() {
  var topo = document.querySelector("#topo");

  var conteudo = document.querySelector("#conteudo");

  var rodape = document.querySelector("#rodape");

  var tamanhoTela = window.innerHeight;

  if (rodape.offsetTop < tamanhoTela - rodape.offsetHeight) {
    conteudo.style.marginBottom = (tamanhoTela - topo.offsetHeight - conteudo.offsetHeight - rodape.offsetHeight - 20) + "px";
  } else {
    conteudo.style.marginBottom = "20px";
  }
}
* {
  margin: 0;
  padding: 0;
}
body {
  background: #ccc;
}
#topo {
  width: 100%;
  height: 150px;
  background: #555;
}
#conteudo {
  width: 80%;
  height: 200px;
  background: #555;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 20px;
}
#rodape {
  width: 100%;
  height: 50px;
  background: #555;
}
<div id="topo" onclick="alert(window.innerHeight)"></div>
<div id="conteudo"></div>
<div id="rodape"></div>

In this way you will have a footer that will not be fixed if the content div is large and there is a scroll on the page, and you also will not have the footer overlapping the content if it is large enough to make the page have scroll

I hope I have helped.

    
08.09.2015 / 18:40
1

Footer at the bottom of the Document

I usually use the following solution:

First calculate the height of the window windowHeight and from that height subtract the height of the header headerHeight and the footer footerHeight then apply the result in the minimum height of the content:

jQuery(document).ready(function($){

  // Aplica a altura toda vez que a janela for redimensionada 
  $(window).resize(function(event){

    // Altura da Janela
    var windowHeight = $(window).height();
    
    // Altura do Cabeçalho (com margins e paddings)
    var headerHeight = $('header').outerHeight(true, true);
    
    // Altura do Rodapé (com margins e paddings)
    var footerHeight = $('footer').outerHeight(true, true);
    
    // Altura mínima calculada
    var contentHeight = Math.floor(windowHeight - headerHeight - footerHeight);
    
    // Aplica a altura mínima necessária para que o footer encoste na parte
    // inferior da janela
    $('section').css('min-height', contentHeight);
  
  }).resize(); // Executa o evento uma vez para que seja aplicada as correções

});
body{margin:0;padding:0;}
header, section, footer{
  color:#FFF;
  text-align:center;
  font-size:20px;
  line-height:80px;
}

header{
  background-color:#764895;
  height:80px;
}
section{
  background-color:#053057;
}
footer{
  background-color:#549276;
  height:30px;
  line-height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><header>Cabeçalho</header><section>Conteúdo</section><footer>Rodapé</footer>

Ifthecontentexceedstheheightofthewindow,nothinghappensvisually,aswearespecifyingtheminimumheight,notthemaximumorspecificheight.We'rejustsayingthatitcannotgetsmallerthanXpixels,butitdoesnotmatterifitgetsbigger.

FooteratthebottomoftheWindow

Now,sothatthefooterisalwaysvisible,evenwhenthereisenoughcontenttocreatescrollingonthepage,useposition:fixed;asfollows:

jQuery(document).ready(function($){

  // Altura do Cabeçalho (com margins e paddings)
  var headerHeight = $('header').outerHeight(true, true);
    
  // Altura do Rodapé (com margins e paddings)
  var footerHeight = $('footer').outerHeight(true, true);
    
  // Aplica uma margem superior no conteúdo do tamanho do cabeçalho, para que
  // o conteúdo seja visível desde o início
  $('section').css('margin-top', headerHeight);
  
  // Aplica uma margem inferior no conteúdo do tamnho do rodapé, para que 
  // o conteúdo seja visível até a última informação
  $('section').css('margin-bottom', footerHeight);
  
  
  // Aplica a altura toda vez que a janela for redimensionada 
  $(window).resize(function(event){

    // Altura da Janela
    var windowHeight = $(window).height();
        
    // Altura do Cabeçalho (com margins e paddings)
    var headerHeight = $('header').outerHeight(true, true);
    
    // Altura do Rodapé (com margins e paddings)
    var footerHeight = $('footer').outerHeight(true, true);
        
    // Altura mínima calculada
    var contentHeight = Math.floor(windowHeight - headerHeight - footerHeight);
        
    // Aplica a altura mínima necessária para que o footer encoste na parte
    // inferior da janela
    $('section').css('min-height', contentHeight);
      
  }).resize(); // Executa o evento uma vez para que seja aplicada as correções
  
  

});
@import url(https://fonts.googleapis.com/css?family=Lato);
body{margin:0;padding:0;font-family:Lato;}
header, section, footer{
  color:#FFF;
  text-align:center;
  font-size:20px;
}

header{
  position:fixed;
  background-color:#764895;
  line-height:80px;
  height:80px;
  width:100%;
  left:0;
  top:0;
}
section{
  background-color:#053057;
}
footer{
  position:fixed;
  background-color:#549276;
  line-height:30px;
  height:30px;
  width:100%;
  left:0;
  bottom:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<header>Cabeçalho</header>
<section>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt voluptate sequi hic dignissimos vel? Sed veniam deleniti dolor, voluptas. Aliquam eius temporibus magnam iure doloribus maxime, impedit cum provident eligendi!</p>
<p>Corporis incidunt, maiores. Recusandae, eveniet corporis est esse ratione quibusdam ipsam deserunt earum a rem id neque aspernatur quos commodi consequuntur non deleniti. Culpa, autem nulla sint, mollitia maiores nobis?</p>
<p>Ratione ipsum sed quis aperiam repellat eum distinctio nemo? Error obcaecati, hic nisi esse, possimus sed qui dolor, corrupti aut nobis molestiae totam. Numquam maiores explicabo ipsum error iusto id.</p>
<p>Nam temporibus labore magnam, sapiente officia beatae quasi libero sequi. Architecto, nostrum! Itaque doloremque nostrum eveniet illo sed reprehenderit, impedit perspiciatis officiis ratione tenetur eligendi placeat explicabo, suscipit laudantium. Earum.</p>
<p>Est eum voluptas aperiam nesciunt doloremque ipsum, architecto nihil, perferendis nam harum natus commodi quam molestias distinctio inventore illo! Nemo minus iste, adipisci totam autem aspernatur, architecto ipsum dicta nam.</p>
<p>Labore deserunt rerum quam alias corporis saepe soluta non perferendis, rem! Repellat repellendus explicabo dolore a aliquam nobis voluptate qui est ea, molestias aperiam dolorum accusantium minima quos consequuntur illo.</p>
<p>Saepe voluptatem aliquam, cumque alias maiores labore debitis atque temporibus et iste magni aut consectetur fugiat ab iure mollitia ea neque ad delectus! Sit earum, repudiandae voluptatum maxime, eos dolorum.</p>
<p>Labore inventore aliquam magnam aspernatur. Numquam officiis illo suscipit quidem nostrum quibusdam id veniam, corrupti temporibus molestias, aperiam voluptatem impedit odit totam pariatur? Sed repellendus nam, reiciendis dolore, suscipit libero.</p>
<p>Rem unde quasi minima, nemo porro nihil accusantium tempore eius placeat atque aut aspernatur explicabo ipsa nesciunt natus delectus. Consectetur possimus fugiat quod asperiores repudiandae quaerat adipisci dolor libero iusto.</p>
<p>Porro omnis cum vitae culpa aliquam, optio provident nesciunt perspiciatis ea doloremque totam sequi magni cumque suscipit error voluptates, quam earum dolorum molestias voluptas perferendis esse. Dolores, ipsam amet at.</p>
</section>
<footer>Rodapé</footer>
    
08.09.2015 / 18:55