Grid: why am I only getting one column?

I want to create four columns. The header, nav, main, and footer should all be 100px-wide columns, but instead, they are all stacked in top in a single 100px column. What’s up?

<style>
body {
  display:grid;
  grid-template-columns: 100px 100px 100px 100px;
}
header {background:blueviolet;}
nav { background: red;}
main {background:gray;}
footer {background:greenyellow;}
</style>

<doctype HTML>
<html>
	<head>
		<title>Grid Test</title>
	</head>
	<body>
    <header>Welcome</header>
    <nav>nav</nav>
    <main>main</main>
    <footer>footer</footer>
	</body>
</html>

You have four columns. I would suggest using the dev tools to inspect the grid, Firefox has a really good Grid inspector, but Chrome can show the grid as well.

I’m just not sure why you want elements that should be stacked on top of each other to be side by side? The layout calls for one column and four rows, not four columns and one row.

If you are going to use a fixed column layout you have to place the grid items, telling them where to start and stop for each column/row.
https://codepen.io/anon/pen/VJbXeN


Check out the Grid course by Wes Bos, read the Grid docs on MDN and the CSS Tricks article.

It is better to put a style tag inside of a head tag. Write <!DOCTYPE html> and give width: 100% to your body and some value of font-size

1 Like

I’m just experimenting, trying to get an understanding of how grid works. (I’m thinking about ideas like having a left-hand column navigation.)

Here’s another example. I have a container div and some items inside. This behaves like I expect. Four columns, one row.

<!doctype HTML>
<html>
	<head>
		<title>Grid Test</title>
<style>
.container {
  display:grid;
  grid-template-columns: 100px 100px 100px 100px;
}
.divA {background:blueviolet;}
.divB { background: red;}
.divC {background:gray;}
.divD {background:greenyellow;}
</style>
	</head>
	<body>
    <div class="container">
      <div class="divA">A</div>
      <div class="divB">B</div>
      <div class="divC">C</div>
      <div class="divD">C</div>
    </div>
	</body>
</html>

Why does this not work when the body is the grid container and the header, nav, etc. are the child grid items?

<body class="container">

I found my mistake: I was missing the exclamation from the html declaration in my original code.

1 Like