Explain Codes LogoExplain Codes Logo

Make footer stick to bottom of page correctly

html
responsive-design
css
best-practices
Anton ShumikhinbyAnton ShumikhinยทDec 23, 2024
โšกTLDR

Cornerstone to your footer's bottom placement comes from harnessing the strength of CSS Flexbox. Spread display: flex, flex-direction: column, and min-height: 100vh on the main container. This ensures it reaches full viewport height. Setflex: 1 to content to push footer down when content is light. Take a look at the code:

html, body { height: 100%; } .container { display: flex; flex-direction: column; //Sending your footer south! min-height: 100vh; //A viewport's worth of adventure } .content { flex: 1; /* Like a jedi push, forcing the footer away */ } .footer { // The sparkly sand to your content's ocean }

The HTML gos as follows:

<div class="container"> <div class="content"> <!-- Main narrative --> </div> <footer class="footer"> <!-- Curtain close --> </footer> </div>

Enjoy your rock-solid foundation, your footer is now immoveable regardless of content quantity. ๐Ÿš€

Crucial concepts explained

Dynamic content and overflow handling

Flexbox might not meet all needs, for instance when dealing with dynamically changing content. Here's an alternative:

  • Set min-height: 100vh for .container. Even with ever-changing content, your steady footer remains at the viewport's edge.
  • Use overflow: auto; to clip any protrusions, keeping the footer right where it should be.

Short and fixed pages

On pages with sparse content, footers tend to levitate. Fixing the footer position can calm this AB-normal-behavior:

.footer { position: fixed; // Grounded. Like your teen self on a Friday night bottom: 0; width: 100%; height: 60px; /* As tall as your favourite hobbit */ }

Align base styles

Consistency is key. Ensure html and body share a wardrobe:

html { position: relative; // Your GPS to the footer min-height: 100%; } body { margin-bottom: 60px; /* Works out to the Footer's height */ }

Footers may show unhelpful margins. Reset this behavior:

.footer { margin-bottom: 0; //Like a perfect lasercut }

Advanced sightings

Flexible containers & dynamic content

Adapt to wildly varying content by deploying flexible containers:

.container { display: flex; flex-direction: column; min-height: 100vh; }

Within its bounds, you can manage varying content:

.content { flex: 1; overflow: auto; // For when content overflows }

Stick with it, or fix it?

Position: sticky; vs position: fixed;:

  • Sticky keeps the footer at the bottom - within its bounds.
  • Fixed glues the footer to the viewport's bottom, regardless of container.

Keep it simple

Steer clear of complex, unneeded solutions. Over-complications can lead to cross-browser problems and harder maintenance.