Full width backgrounds and centering page content in 16 lines of CSS

2021-08-16

Discovered a way how you can center the main content of the page to a fixed width value in full-width view and also have a full width background at the same time.

The defined media query will add padding to the main content so that there is some space between the edges of the screen.

Been using this in all of my projects, very helpful stuff.

Required CSS

:root {
  --max_width_1: 955px;
}
.max_width_1 {
  width: var(--max_width_1);
}
.flex_center {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
@media screen and (max-width: 1200px) {
  .max_width_1 {
    padding: 0px 50px;
  }
}

Required HTML

<div class="flex_center">
  <div class="max_width_1 ">top block</div>
</div>