Fixed header in CSS Grid
Once you set a child of a grid container to position: fixed
it is removed from the document flow and no longer participates in grid layout (see section 9.2 of the grid spec).
Therefore, it makes sense to remove an element from a grid container if you want it fixed to the viewport. If it's a header, just place it above the grid container.
If you still want the header to be a grid that's not a problem. Fixed elements can be grid containers. They just don't do well as grid items.
codepen demo
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
body {
line-height: 1;
}
ol,
ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* DEFAULTS */
body {
color: white;
}
/* SETTING UP THE GRID LAYOUT */
.wrapper {
display: grid;
grid-template-columns: repeat(12, [col-start] 1fr);
grid-template-rows: 1fr;
height: 90vh;
overflow: auto;
}
.header {
height: 10vh;
background-color: black;
}
.jumbotron {
grid-column: col-start / span 12;
height: 30vh;
background-color: yellow;
}
.content-one-left {
grid-column: col-start / span 6;
height: 30vh;
background-color: red;
}
.content-one-right {
grid-column: col-start 7 / span 6;
height: 30vh;
background-color: blue;
}
.content-two-left {
grid-column: col-start / span 6;
height: 30vh;
background-color: blue;
}
.content-two-right {
grid-column: col-start 7 / span 6;
height: 30vh;
background-color: red;
}
.footer {
grid-column: col-start / span 12;
height: 10vh;
background-color: black;
}
<div class="header">
<p> Header </p>
</div>
<div class="wrapper">
<div class="jumbotron">
<p> Jumbotron </p>
</div>
<div class="content-one-left">
<p> Content 1 Left </p>
</div>
<div class="content-one-right">
<p> Content 1 Right </p>
</div>
<div class="content-two-left">
<p> Content 2 Left </p>
</div>
<div class="content-two-right">
<p> Content 2 Right </p>
</div>
<div class="footer">
<p> Footer </p>
</div>
</div>
In 2018, you can use position: sticky
header {
position: sticky;
top: 0;
}
Here is a JSFiddle demoing it.
Browser support - it works for the header
element (tested in Chrome and Edge).