How to center a Layout

How to center a Fixed Width Layout

Centering an entire layout is easy in CSS. Wrap all you HTML in some kind of container, usually a div:

<body>
   <div class="container">

      <-- All of the content in here -->

   </div>
</body>
We can use CSS flexbox to center the container div easily. All we have to do is:
body {
  display: flex;
  justify-content: center;
}

.container {
  width: 80%;
}

Setting a max-width

Using percentages for your page width allows for flexible pages, however we need to be mindful of line lengths. Blanket percentage widths on very large screens will cause readability issues. It's good practice to also specify a maximum page width to ensure that the line lengths of your text do not get too long.

Use the same HTML:

<body>
  <div class="container">

    <-- All of the content in here -->

  </div>
</body>
.container {
  margin: 0 auto;
  width: 80%;
  max-width: 1024px;
}

Non Flexbox approach

There is also an older method for centering which uses automatic margins.

.container {
  margin: 0 auto;
  width: 80%;
}