Use CSS Clamp to create a more flexible wrapper utility

Categories

A handy way to use modern CSS functions to give yourself fine-grained, yet flexible, design control.


You can use clamp() to set three values: a minimum, an ideal and a maximum.

This is really handy in the context of a wrapper, because it’s a mostly fluid element, often limited with a max-width. This becomes a slight issue in mid-sized viewports, such as tablets in portrait mode, in long-form content, such as this article because contextually, the line-lengths feel very long.

An article where the content is very tight to each side of the viewport

Even though the line lengths are set to a sensible width in CSS, contextually, they still look very long in medium viewports.

If we use clamp() to use a viewport unit as the ideal and use what we would previously use as the max-width as the clamp’s maximum value, we get a much more flexible setup.

Code language
css
/**
 * WRAPPER
 * Sets a max width, adds a consistent gutter and horizontally
 * centers the contents
 */
.wrapper {
  width: 90vw;
  width: clamp(16rem, 90vw, 70rem);
  margin-left: auto;
  margin-right: auto;
  padding-left: 1.5rem;
  padding-right: 1.5rem;
  position: relative;
}

Here’s how it looks after setting our new wrapper:

An article where the content has much more room horizontally

This is much better now and the content looks like it has much more breathing room, making it easier to read.

This is a very small tweak, but these design details are what makes the user-experience that little bit better. Check out this handy write-up by Una Kravets.

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.