DEV Community

Mike Mai
Mike Mai

Posted on • Edited on

1 1

Setting content max-width in 2021

Y'all are familiar with something like this in your code:

<body>
  <div class="wrapper">...</div>
</body>
Enter fullscreen mode Exit fullscreen mode

By having a wrapper, you limit the content on your site to not exceed a certain width (e.g. 1000px). The CSS for the wrapper usually looks like this:

.wrapper {
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
  padding-left: 2rem;
  padding-right: 2rem;
}
Enter fullscreen mode Exit fullscreen mode

That has certain limitations, the most glaring one being that you cannot use background color or background image on this element due to the width being set (usually you'd work around this by setting background on <body> or nest the wrapper inside another full-width element with background). And honestly, that is so much CSS for something that is kind of trivial.

We are in 2021, and CSS is very powerful. I can actually change the max-width to something more fluid:

.wrapper {
  max-width: min(80vw, 75ch);
  ...
}
Enter fullscreen mode Exit fullscreen mode

Awesome! Now my content feels pretty damn comfortable to read in all viewports (it is 80% wide but does not go beyond 75 characters). However, that is not enough. It is still TOO MUCH CSS.

I think I am gonna reduce it to 1 CSS var and 2 lines of padding rules:

:root {
  --page-padding-x: calc((100vw - min(80vw, 75ch)) / 2);
}

.section {
  padding-right: var(--page-padding-x);
  padding-left: var(--page-padding-x);
}
Enter fullscreen mode Exit fullscreen mode

Hell yeah! That is more like it. It achieves the same goal of setting a max-width but now I can even use background color or background image without needing to write extra markup.

This element has evolved and I am renaming it to section. I can basically create multiple sections on a page with this and I can give my content some fancy zebra striping if I so desire:

<body>
  <div class="section black">...</div>
  <div class="section white">...</div>
  <div class="section black">...</div>
  <div class="section white">...</div>
</body>
Enter fullscreen mode Exit fullscreen mode

As for the CSS var, I can use that on header and footer as well. Woot!

Goodbye, wrapper. I will not miss ya.

EDIT: demo codepen.

EDIT 2: browser support for min()

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay