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>