Best way to center content with css

The following is an easy way to align content in the center of the page without having to use breakpoints.

.container {
  --container-margin: 2rch;
  --container-width: 65rch;
  max-width: min(
    calc(100dvw - var(--container-margin)), 
    var(--container-width)
  );
  margin: auto;
}

How it works

  1. The rch is the relative character width as defined in the root element (such as the <html> or <body>.
  2. I'm using 2rch so that I will at least one(!) space on the left, and another on the right.
  3. The max-width takes the smallerst value of either:
    1. the viewport minus the margin
    2. the max width that I allow (65rch)
  4. The margin: auto will cause the element to be placed in the center.

Why this method?

I often have pages that require slightly different layouts. First of all, this method doesn't require a wrapper element (such as grid/flex). It's easy to manage while also respecting content, and unlike padding it only adds spacing around when needed.

And if needed I can move the --container-margin variable and --container-width variable up to my variables stylesheet so that I can still introduce media query checkpoints.

Mastodon