I'm trying to build a layout with CSS Grid. I want the header element to be 'sticky'. That is, when the user scrolls, the header stays fixed to top of viewport and other content scrolls up and underneath header. I'd like to give this header a background image.
I've assigned a background image to the header, given it a position value of fixed and applied a z-index value of 999. Other elements below have been positioned and given lower z-index values.
My problem is that this setup doesn't work. I tried a few variations on the CSS but the background image either completely disappears or, on scroll, the header does not stay above other elements as they move up the screen.
What am I doing wrong? I browsed other questions in this forum and also on the web in general but can't find an answer.
Any suggestions much appreciated.
My code is shown below (including various changes to CSS - commented out in most cases).
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>
z-index. addposition: fixedon your header and give it awidthandheightthen alsoz-indexof 1