Minimum Margin (calculated max-width)

I was working on a site where the search results took 100% of the page width, meaning there was no margins on the sides. This looks bad (subjectively) and is worse on mobile when the text is right up against the phone's bezel.

There are a number of ways we could add some whitespace to the left and right of the results. We could use media queries to set different max-widths, which really isn't a bad idea at all. However, I came across a CodePen by Ragdoll that is interesting, simple, and works great on a search page: minimum margins.

I will point out that CSS standards do not define a min-margin tag. If they did, this wouldn't be all that interesting. Instead, we can use the calc function define the maximum width as 100% minus whatever we want the margin to be. Even if we define our content to be 100% width, it will restrict it to the maximum calculated width.

Here's a sample (in case the CodePen disappears):

HTML

<div class="page">
  <div class="wrapper">
    <p>Some content that will have a calculated max width</p>
  </div>
</div>

CSS

.page {
  width: 100%;      // Width of the container
  max-width: 100%;  // Maximum width of the container set to full width
}

.wrapper {
  width: 100%;      // Wrapper will try to be 100% of the container
  max-width: calc(100% - 20px); // But the maximum width will be 20px less
  margin: auto;     // Just so we center the wrapper
}

So even though we have told the page and the wrapper to have a width of 100%, the calculated width of the wrapper is 100% - 20px (replace the 20px with double whatever you want the margins to be), so it will be restricted. This works with explicit pixel widths as well.

This is a simple solution that takes care of an occasional problem. In fact, it's one of those that makes me go "duh, that's rather obvious".