How to keep the footer always down there

Asked

Viewed 19,009 times

6

I wanted to know how to keep the footer of the site always at the bottom of the site, even if the content of the site is little, as the example below.

Exemplo

If I put a margin top, it doesn’t stay down there in all resolutions, I tried it with percentage and also failed.

  • 1

    have tried bottom: 0px?

  • Hadn’t tried, thanks ai @Tobymosque gave it right!!

  • http://getbootstrap.com/getting-started/#examples Use the example named: Sticky footer

  • Thanks @João, I didn’t want to use bootstrap, because it’s a simple page, just needed to adjust the footer, but in this example has a css only for this, I liked it well!

5 answers

9


you can fix an element at the end of the page using position fixed or absolute and set the bottom for 0px.

Follow an example with header and footer fixed and the 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>

7

For me the most sensible way and without gambiarra is to use Calc, with it you avoid using position Absolute or javascript often forcing the reflow and overlapping elements with z-index, not to mention avoids several bugs and is supported in almost all browsers, with the exception of some mobile browsers.. However I do not worry about it, because usually there is scrolling on the page vertical axis in 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>

3

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>

2

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

Explaining the code:

What I did was this, I made sure that when the page was loaded or redeemed, it would perform a function. This function evaluates whether the wheel is in a higher position than the lower part of the window, if yes it positions it using the following values for the lower margin of the contents div:

  • sizeTela => window height
  • top.offsetHeight => top div height
  • Content.offsetHeight => height of the content div
  • footer.offsetHeight => height of the footer div
  • 20 => upper margin of the contents div

Otherwise apply only a margin of 20px to 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>

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

I hope I’ve helped.

2

Footer at the bottom of the Document

I usually use the following solution:

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

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>

If the content exceeds the height of the window, nothing will happen visually, because we are specifying the minimum height and not the maximum or specific. We’re just saying it can’t get any smaller than X pixels, but there is no problem if it gets bigger.

Footer at the bottom of the Window

Now, so that the footer is always visible, even when there is enough content to create scrolling on the page, use position:fixed; as follows:

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>

  • Thanks ai Kadu, I found it a bit "complex", I managed to do it another way, but thanks really, I liked your solution, I did not know this way to get the page height.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.