Creating a CSS3 Grid Layout with a Fixed Header

I'm having some trouble creating a layout using CSS Grid. My goal is to make the header element 'sticky', so that it remains fixed at the top of the viewport while other content scrolls up and underneath it. Additionally, I want to add a background image to this header.

To achieve this, I have set a background image for the header, assigned it a position value of fixed, and given it a z-index of 999. Other elements below have been positioned with lower z-index values.

However, my current setup is not working as expected. Despite trying various CSS adjustments, the background image either disappears entirely or the header does not stay above the other elements as they scroll up the screen.

I have searched through this forum and other online resources but have not been able to find a solution to my issue.

If anyone has any suggestions, I would greatly appreciate it.

Below, you can find my code snippet (including some commented out CSS changes):

    body {
    display: grid;
    grid-template-areas: "header header header" "nav article ads" "footer footer footer";
    grid-template-rows: 250px 900px 70px;
    grid-template-columns: 20% 1fr 15%;
    grid-row-gap: 10px;
    grid-column-gap: 10px;
    height: 100vh;
    margin: 0;
    }
    header {
    /* position:fixed;
    z-index:999;*/
    }
    footer, article, nav, div {
    padding: 1.2em;
    background: gold;
    }
    #pageHeader {
    grid-area: header;
    padding: 1.2em;
    background: url(https://placeimg.com/50/250/arch) left top repeat-x fixed;
    }
    #pageFooter {
    grid-area: footer;
    }
    #mainArticle {
    grid-area: article;
    position: relative;
    z-index: 9;
    }
    #mainNav {
    grid-area: nav;
    position: relative;
    z-index: 8;
    }
    #siteAds {
    grid-area: ads;
    position: relative;
    z-index: 7;
    }
    /* Stack the layout on small devices. */

    @media all and (max-width: 575px) {
    body {
    grid-template-areas: "header" "article" "ads" "nav" "footer";
    grid-template-rows: 80px 1fr 70px 1fr 70px;
    grid-template-columns: 1fr;
    }
    }
<body>

  <header id="pageHeader">Header</header>

  <article id="mainArticle">Article</article>

  <nav id="mainNav">Nav</nav>

  <div id="siteAds">Ads</div>

  <footer id="pageFooter">Footer</footer>

</body>

Answer №1

To achieve the desired effect, make sure to eliminate any conflicting z-index values from other elements. Apply a style of position: fixed to your header, specifying both a width and a height, and set its z-index to 1 as well.

An element positioned absolutely functions like layers in a way. The z-index property in combination with the DOM (where x and y represent 2D coordinates, and z represents stacking) dictates the positioning within the structure.

For further insights, consider delving into this resource for an in-depth explanation—I may risk muddling things if I attempt to elaborate more extensively.

Answer №2

Move your <header> element outside of the grid structure in your HTML. Currently, the entire grid is encompassing the header because it's placed within the body tag that has the display: grid; property. To fix this, create a container inside the body with the display: grid; style and place the header outside of that container. Here is an example:

HTML:

<body>

    <header>Header content!</header>

    <div class="container">

        <div class="mainNav"></div>
        <div class="sidebar"></div>
        <div class="siteAds"></div>
        <!-- etc. -->

    </div>

</body>

And the CSS:

body {
    /* Your regular body styles here */
    /* Remove display: grid; from body */
}

header {
    position: fixed;
    z-index: 10;
    height: 100px;
}

.container {
    display: grid;
    margin-top: 100px; /* Adjust for header height */

    /* Add your other grid styles here */

}

Remember to keep the header separate from the grid layout for proper functionality.

Answer №3

Check out the Jsfiddle link for an interactive example...

I've included some custom CSS styles and jQuery code

CSS Styles

#pageHeader.fixed {
    position: fixed;
    top:0; 
    left:0;
    width: 100%;
    z-index: 99;
}

jQuery Code

$(window).scroll(function(){
    var sticky = $('#pageHeader'),
    scroll = $(window).scrollTop();

    if (scroll >= $('#pageHeader').height()){
        sticky.addClass('fixed');
        $('#pageHeader').addClass('fixed');
    } else {
        sticky.removeClass('fixed');
        $('#pageHeader').removeClass('fixed');
    } 
});

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

jQuery Alert for Double-Checking Email Entry

Is it possible to create a simple alert pop-up using jQuery if the user does not enter the correct email address in the second email input form? Below is my current code: <div id="reservation-request"> <form method="post" action="test.php ...

Creating a new tab within a window that is already open

I have an interesting challenge - I need to open a new tab in a window that was previously opened using window.open(). So, if the window is already open, I want to open a tab in that same window. I have attempted to reference the existing window to open a ...

When implementing flex-grow 1 on a flex box, the remaining space is not being filled as expected

I am struggling to make the green div fill the remaining space of a flex box container. My goal is to have the top row (blue) adjust its height based on content, and then have the row below (green) take up the rest of the space. However, it seems like the ...

Fetch HTML content from a local file using Vue

I am currently searching for a method to import HTML content from a file located at /src/activities/0/2/content.html The specific numbers in the path are interchangeable variables. My goal is to achieve something along the lines of mounted(){ this ...

Using Angular, you can effortlessly inject elements into the editable div from any location on the page

Currently, I am working on developing an HTML interface that allows users to input text and send it as a notification to our mobile application. However, I am encountering challenges with the text and dynamically inserted elements using Angular 5; The te ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

What is preventing this from functioning in IE10 while it works fine in IE7?

I am currently facing an issue with a form that has been divided into three sections, each with a "next" and "back" button to navigate through the sections. The functionality works perfectly in Firefox, Chrome, and IE7, but not in IE10+. Specifically, the ...

What are some ways I can showcase the outcomes of my multiple choice quiz?

I need help with my multiple choice quiz. I want to display the answers under each question and highlight the correct one in bold. Here is the current code: function check() { var question1 = document.quiz.question1.value; var question2 = document.q ...

Ways to remedy the white line produced by CSS transform when hovered over?

Has anyone discovered a fix for the white line or border that appears when an element is transformed with CSS scale on hover? I've tried various solutions such as: transform: translateZ(0), -webkit-backface-visibility: hidden, transform-style: preser ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

Utilizing Multiple Components on a Single Page in React.js

I'm currently setting up a React main page that renders two separate components - Header and Test. render() { return ( <Header /> <Test /> ); } The Header component contains static content, while the ...

The HTML2Pdf content is spilling over the edge of the page

I am attempting to create a PDF from an HTML File using the HTML2PDF library. Here is my HTML code: <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" valign="top"> <table width="968" ...

There was an error loading the resource as the Object does not have the method 'adGallery'

For the past two days, I have been attempting to implement the jQuery plugin "ad-gallery" on my website without success. I must mention that my knowledge in JavaScript and CSS is limited, so the issue could be something simple. The peculiar thing is that ...

Can anyone provide guidance on how to create this particular shadow effect using CSS?

Is there a method to use CSS to create a green shadow in that particular shape? ...

Guide on finding and replicating a particular string in HTML connected websites

Allow me to outline the issue at hand. By visiting the provided link, you will encounter a directory of html links containing stories by Aesop, each with its own moral. My goal is to extract and save only the strings that include "Moral of Aesop's Fab ...

Determining the repetition and placement of background images when employing multiple backgrounds

Is it possible to apply two background images to the same div? I want one image to repeat along the x-axis and the other to appear only once. I've tried using multiple background images, but I'm not sure how to target specific rules for each bac ...

Is it possible for me to create an HTML script that can transfer data from the script to a cell within Qubole?

Is it possible to create an HTML script that allows user interaction, pass the data back to a zeppelin cell, and trigger a rerun of the data? Thank you! Update: I have made some progress in rerunning the cell with an HTML click. The cell I want to rerun ...

I am looking to transform col-sm-4 into two evenly sized columns with one row at the bottom using Twitter Bootstrap

Hello there, I have successfully created three columns in one row with column sizes of col-sm-4 each. Each column is further split into two equal sections and includes a footer row. You can see the alignment in the image below: Check out this sample align ...

Differences between Animation Easing in iOS and CSS3 Cubic Bezier Functions

I am currently working on an iOS app and I am trying to improve the animations within it. Having a lot of experience with CSS3 animation and transitions, I want to be able to define my animations in iOS with the same precision that is possible with CSS3 ( ...