CSS Grid simplifies web layout significantly. While there's a learning curve, its intuitive nature makes it enjoyable to use, especially for managing headers and footers. This tutorial demonstrates creating both fixed and sticky footers using CSS Grid. Rachel Andrew's "The New CSS Layout" is highly recommended for a deeper dive into Grid and Flexbox.
Project Overview
We'll build a classic HTML layout with a header, main content, and footer. We'll implement two footer variations: a fixed footer that remains at the viewport bottom regardless of content length, and a traditional sticky footer that adheres to the bottom but is pushed down by longer content. The main content area will be adaptable, spanning the full viewport width or centering within a defined width.
Fixed footers, while less common than sticky footers, are used by sites like Charles Schwab. Their implementation often involves hard-coded sizes and paddings. Our approach avoids these limitations, leveraging CSS Grid's flexibility.
Before proceeding, examine the Charles Schwab homepage's fixed footer. Inspecting its code in DevTools reveals hard-coded height and positioning.
Let's achieve a similar effect without these constraints.
Initial Styles
We'll start with a minimal UI, gradually enhancing it with CSS Grid. A CodeSandbox (and subsequent iterations) provides interactive examples.
First, we ensure the viewport's full height is utilized:
body { margin: 0; /* prevents scrollbars */ } #app { height: 100vh; }
Next, we define the header, main, and footer sections and their grid structure. This initial structure won't function as intended yet; it serves as a foundation:
body { margin: 0; } #app { height: 100vh; /* grid container settings */ display: grid; grid-template-columns: 1fr; grid-template-rows: auto 1fr auto; grid-template-areas: 'header' 'main' 'footer'; } #app > header { grid-area: header; } #app > main { grid-area: main; padding: 15px 5px 10px 5px; } #app > footer { grid-area: footer; }
This creates a single-column layout. 1fr
means "take the remaining space," resulting in full-width columns. The rows are sized using auto
(for header and footer) and 1fr
(for main content to fill remaining space). No hard-coded heights are necessary.
Content Integration
The provided CodeSandbox uses React for demonstration purposes, but the CSS Grid principles remain independent of the framework. Header, Main, and Footer components render the respective HTML elements. Billing and Settings sections provide sample content, demonstrating the layout's adaptability.
The initial layout shows a functional "Billing" section, but "Settings" pushes the footer off-screen. Scrolling affects the entire page, causing the header to disappear. Let's address this.
Fixed Header and Footer
The 100vh
height and auto
/1fr
row sizing initially cause issues when content exceeds the viewport. Adding overflow: auto
to the <main></main>
element enables scrolling within the main content area, keeping the header and footer fixed:
#app > main { grid-area: main; overflow: auto; padding: 15px 5px 10px 5px; }
This updated demo resolves the scrolling and visibility issues.
Adjustable Main Section Width
To center the main content within a 600px width or allow it to span the full viewport, we nest a grid inside <main></main>
. This uses three columns (1fr 600px 1fr
), effectively centering the 600px section.
#app > main { display: grid; grid-template-rows: 1fr; grid-template-columns: 1fr 600px 1fr; }
Content is positioned using grid coordinates. A .full
class allows content to span the entire width:
#app > section { grid-area: 1 / 2 / 1 / 3; } #app > section.full { grid-area: 1 / 1 / 1 / 4; }
Note the use of grid lines (four lines for three columns). Shrinking the viewport reveals a truncation issue with the fixed 600px width. minmax(0, 600px)
solves this, allowing the width to adjust up to 600px:
main { display: grid; grid-template-rows: 1fr; grid-template-columns: 1fr minmax(0, 600px) 1fr; }
The final demo showcases this responsive behavior.
Traditional Sticky Footer
To create a traditional sticky footer, we modify the grid structure. The <main></main>
element now contains the footer within its grid:
<div> <header></header> <main> <section></section> <footer></footer> </main> </div>
The #app
grid is updated to have two rows:
#app { /* same as before */ grid-template-columns: 1fr; grid-template-rows: auto 1fr; grid-template-areas: 'header' 'main'; }
The <main></main>
grid is adjusted to include the footer:
#app > main { display: grid; grid-template-rows: 1fr auto; grid-template-columns: 1fr minmax(0, 600px) 1fr; }
Footer positioning within this grid:
#app > footer { grid-area: 2 / 1 / 3 / 4; }
This setup allows the footer to be pushed down by content within <main></main>
, creating the desired sticky footer effect. Minor padding adjustments were made to ensure proper alignment. The final demo illustrates this behavior. Additional styling was applied to the section element to allow horizontal scrolling within the content area while maintaining the vertical layout.
Conclusion
While the techniques demonstrated are achievable without CSS Grid, Grid provides a unified and elegant solution. Its flexibility and ease of use, as demonstrated by the simple transition from a fixed to a sticky footer, make it a powerful tool for complex layouts. The examples presented are relatively simple, showcasing the potential of CSS Grid for more ambitious projects.
The above is the detailed content of How to Use CSS Grid for Sticky Headers and Footers. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

CSSCounters is a tool for creating automatic numbers. 1. Basic usage: define and operate counters through counter-reset and counter-increment, such as "SectionX." before h2. 2. Advanced usage: Use nested counters to create complex numbers, such as chapter and section numbers. 3. Notes: Ensure the counter is reset correctly, optimize performance, and simplify counter logic. 4. Best practice: clear naming, define counters in CSS, and use counter-increment and counter-reset reasonably.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.
