DEV Community

loading...

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

tompston
・1 min read

Discovered a way how you can center the main content of the page to a fixed width value in full-width view AND 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Required HTML

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

Enter fullscreen mode Exit fullscreen mode

Open on Codepen to see the working example!

Discussion (0)