Anders Grendstadbakk

CSS Calc is pretty neat

With a centered layout it can be hard to have full with elements without a hassle.

In this post will I show you a neat trick to get full width sections in a layout that are centered. If you just want the demo check out this CodePen.

The snippet should work in Internet Explorer 9 and up and the other major browsers.

.full {
  left: calc((100% - 100vw)/2);
  position: relative;
  width: 100vw;
  min-height: 1px;

  // Optional (center padding both sides):
  padding-left: calc((100vw - 100%)/2);
  padding-right: calc((100vw - 100%)/2);
}

{: .language-scss}

The how

The vw unit is the width of the viewport. 100vw is the width of your browser window, 50vw is half.

The left property is where the magic happens:

calc((100% - 100vw)/2)

Extra options

To center the content inside the full width element we add padding to both sides by flipping the calc function:

padding-left: calc((100vw - 100%) / 2);

I have created a simple demo on CodePen you can explore, with examples for right and left padding only.

See the Pen CSS Calc examples by andeersg (@andeersg) on CodePen.