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
- The
rchis the relative character width as defined in the root element (such as the<html>or<body>. - I'm using
2rchso that I will at least one(!) space on the left, and another on the right. - The max-width takes the smallerst value of either:
- the viewport minus the margin
- the max width that I allow (
65rch)
- The
margin: autowill 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.