Keep the footer fixed at the bottom until the document height exceeds the viewport height

UPDATE

Originally flagged as a duplicate, I mistakenly labeled it before actually testing the solution in the linked question. The provided answer did not meet my specific requirement of having a sticky footer that only floats to the bottom of the page when the content exceeds the viewport size.

/UPDATE

UPDATE2

I discovered a suitable solution on this website, which utilizes pure CSS and perfectly fulfills my needs.

/UPDATE2

I am looking for a way to keep the footer sticky until the document height surpasses the viewport height, at which point it should naturally align itself with the end of the document.

The structure of the document is as follows:

<body>
    <div class="header">
        <!-- content -->
    </div>
    <div class="page-content">
        <!-- content -->
    </div>
    <div class="footer">
        <!-- content -->
    </div>
</body>

JSFiddle link

The .header has a height of 101px, while the .footer stands at 173px.

The height of .page-content varies based on the content within it.

My desired outcome is for the .footer to remain fixed at the bottom of the viewport unless the document height exceeds that of the viewport.

I attempted setting a min-height for .page-content to always overflow the viewport, but this resulted in an unattractive layout.

Is achieving this solely through CSS possible, or would JavaScript/JQuery be necessary?

Answer №1

Two modern techniques that can be implemented are utilizing calc and flexbox. Both have good browser support (over 90% without prefixes for calc and with prefixes for flexbox). Integrating them is relatively straightforward, especially in comparison to older methods. For enhanced compatibility, viewport units can further simplify implementation.

Technique One - Calc:

CSS:

/* Only required if not using vh in main */
html, body {
  height: 100%;
}

header {
  /* Must be static */
  height: 70px;
}

footer {
  /* Must be static */
  height: 30px;
}

main {
  /* Can substitute 100vh instead of 100% */
  min-height: calc(100% - 70px - 30px);
}

HTML:

<header></header>
<main></main>
<footer></footer>

DEMO: codepen

Technique Two - Flexbox:

CSS:

body {
  display: flex;
  flex-direction: column;
  /* If using percent then html needs a height of 100% */
  min-height: 100vh;
}

main {
  flex: 1;
}

HTML:

<header></header>
<main></main>
<footer></footer>

DEMO: codepen

The flexbox approach offers flexibility as header and footer can adjust dynamically. The flex: 1; property in main ensures it fills any remaining space after header and footer consume their required space. Although the calc method may require static dimensions for header and footer, it does not necessitate prefixes. Personally, both methods work well for me, aided by autoprefixer or prefixfree to handle any prefix concerns.

Answer №2

If you're in need of a sticky footer solution, consider checking out Ryan Faits' "HTML 5 Sticky Footer."

CSS:

* {
  margin: 0;
}
html, body {
  height: 100%;
}
.wrapper {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  margin: 0 auto -4em;
}
.footer, .push {
  height: 4em;
}

HTML:

<html>
    <head>
        <link rel="stylesheet" href="layout.css" ... />
    </head>
    <body>
        <div class="wrapper">
            <p>Your website content here.</p>
            <div class="push"></div>
        </div>
        <div class="footer">
            <p>Footer Content here</p>
        </div>
    </body>
</html>

In this demonstration, the footer is set to be 4em in height. Feel free to customize it by adjusting the "margin" property of the ".wrapper" and the "height" property of the "footer".

Answer №3

To ensure your footer stays at the bottom of the viewport, you can apply this CSS code:

.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 173px;
}

Answer №4

Take a look at this innovative code snippet:

$(function () {
  $(".large-content").hide();
  $("a").click(function () {
    $(".large-content").toggle();
    fixHeight();
  });
  fixHeight();
});

function adjustHeight() {
  if ($(window).height() >= $(document).height())
    $("body").addClass("fixed-footer");
  else
    $("body").removeClass("fixed-footer");
}
* {font-family: 'Segoe UI'; font-size: 10pt; margin: 0; padding: 0; list-style: none;}
p {margin: 0 0 10px;}
.header, .footer {text-align: center; color: #fff; background-color: #000;}
body.fixed-footer {padding-bottom: 2em;}
body.fixed-footer .footer {position: fixed; width: 100%; bottom: 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="header">
  Header Section
</div>
<div class="page-content">
  <p>Small Content</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat aliquam error quas culpa, sapiente sunt asperiores impedit ipsa cupiditate tempore, molestias, vitae laboriosam suscipit pariatur odit? Cumque fugiat iste provident.</p>
  <p><a href="#">Click for large content!</a></p>
  <div class="large-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas est quos officia repellat debitis molestiae incidunt et consequatur ut, dicta rerum qui delectus impedit saepe suscipit explicabo dolorem at ea?</p>
    <p>... (more repeat paragraphs) ...</p>
  </div>
</div>
<div class="footer">
  Footer Section
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountering issues with jQuery Ajax: Dealing with HTTP 405 or

When accessing a web service using jQuery Ajax that uses .asmx, I am encountering HTTP 405 and sometimes 500 errors. Is this a problem with the web service or on the client side? Please provide guidance with an example. $j.ajax({ type: ...

Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the cur ...

Utilizing Bootstrap 5 with either a 16 or 24 column grid system minus the need for Sass

I'm looking for assistance in adjusting Bootstrap 5 to have either a 16 or 24 column grid rather than the default 12 columns. I attempted using Bootstrap Customize but found it to be an older version. I want the flexibility to change the grid from 12 ...

Using Jest to mock a single function within a class

I'm a beginner when it comes to node and javascript, and I am currently attempting to create a unit test using jest where I only need to mock one function of a class (and object). Below is the code template I am using: // myModule.js class MyModule ...

Unable to apply CSS modifications to child elements in AngularJS

angular.element($document[0].querySelector("table > tbody > tr")).mouseover().css("background-color", "red"); <table> <thead> <tr> <th>Name</th> < ...

Stop a Post Request from being processed once a form has been submitted to an IFrame

Is there a way to cancel a post after submitting a form to an IFrame? $form = jQuery("<form target='iframetarget' method=post><files...></form>"); $form.submit(); I am looking for a method like $form.cancelPost(); to stop the ...

Submit information to the table: each entry in the table displays as a value of 1

I've encountered an issue with the script on my server. When the postdata is passed, all fields in the database are populated with the number 1 instead of the actual data. <?php $servername = "localhost"; $username = "tadmin_admin"; $password = "R ...

Here's a way to display 4 <li> elements in a single row and the remaining 4 <li> elements in another row

I'm struggling with a PHP query that retrieves multiple images from a database. My goal is to display 4 images on the first row, another 4 on the second row, and so forth. I initially thought I could achieve this using CSS, but unfortunately, I haven ...

Unidentified googletagmanager detected in vendors segment

Recently, my ad blocker detected an unfamiliar Google Tag Manager request originating from a chunk provided by one of my vendors. Is it typical for tracking to be embedded in dependencies like this? And what type of information can be collected from my we ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

Positioning an image so that it is perfectly aligned on top of another image that is centered

http://jsfiddle.net/Weach/1/ The issue at hand involves a background image created using CSS. This image has been center aligned both horizontally and starting from the top, as visible in the provided JSFiddle link. Specifically, there is another image t ...

Leveraging the power of HTML tags within PHP

myfile = mysql_query($query_myfile, $db) or die(mysql_error()); $totalRows_myfile = mysql_num_rows($myfile); $typ_d = ''; $test=''; while ( $row_myfile = mysql_fetch_assoc($myfile) ) { if ( $typ_d != $row_myfile[ 'typ_d' ...

Position the div alignment to the top within the table cell

I'm having trouble aligning the div under the header to the right. Here is my HTML code and a photo for reference: HTML Code: <td> <div class="schedule-content"> <div class="timestamp& ...

Utilize jQuery, Flash, or HTML5 to upload an image

Does anyone know of an upload tool or plugin that has a similar look and functionality to the one used on Codecanyon's website? I tried Uploadify, but it doesn't work on all browsers. I need something that is compatible with all browsers, whether ...

Master the art of fetching response data from an API and implementing a function to process the data and generate desired outputs using Node.js and JavaScript

Being new to node.js, javascript, and vue, I attempted to create a Currency Converter by fetching data from an API for exchange rates and performing calculations in a function. Despite successfully obtaining the exchange rates from the selected country in ...

Styling with CSS in Play Framework version 2.0.3

Running into issues when using CSS in Play Framework 2.0.3 and could really use some help spotting where I'm going wrong. My view, called siteview.scala.html, is defined as: @(name: String, records: List[Record]) @import helper._ @main(name) { < ...

The order of console outputs can be inconsistent and may not always align with the order in which they are called

Hello there! I'm diving into the world of JavaScript and have a query to share on Stackoverflow. If something seems missing in my question, please do point it out for me. Question 1: Can someone shed light on why the output sequence in the console s ...

Updates to the Tailwind file are not appearing on the page after reopening the file

Every time I reopen the project, the file tailwind properties do not get rebuilt and if I add new properties like text-color, they are also not reflected. Any suggestions on how to solve this issue? I need the project to update and take in new properties ...

"Header background image gradually fades out and disappears as you scroll, revealing a bottom gradient effect in a React application

When I scroll, my header image fades away. I used JavaScript in my React app to achieve this effect: useEffect(() => { const handleScroll = () => { if (parallaxDiv.current) { parallaxDiv.current.style.backgroundPositionY = `${ ...

Interactive pop-up window featuring a top section, main content, and bottom section

I have a situation where I've created a modal with sticky headers and footers, and the middle section scrolls based on the content. Everything looks great on Desktop, but when viewed on mobile or tablet devices, the footer is stretched and not fully ...