The one-liner for max-width, centering, and margins.

Chris Coyier Chris Coyier on

To horizontally center an element and limit it’s width, this is easily the most common approach:

.page-wrap {
  max-width: 1000px;
  margin: 0 auto;
}Code language: CSS (css)

That could still touch the edges of a parent container though, so if need to enforce some spacing, we’d probably do that on a parent.

body {
  padding: 0 1rem;
}Code language: CSS (css)

There is no real problem with that, but we can smash it all into a one-liner now if you’re feeling it:

.page-wrap {
  margin-inline: max(1.5rem, ((100% - 500px) / 2));
}Code language: CSS (css)

The 1.5rem is the space on the outside (which could be 0), and the 500px is the max-width (or rather max-inline-size as we’re using logical properties here).

Wanna learn CSS from a course?

Frontend Masters logo

FYI, we have a full CSS learning path with multiple courses depending on how you want to approach it.

7-Day Free Trial

Leave a Reply

Your email address will not be published. Required fields are marked *

$871,946

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.