CSS magic to size a container for any viewport

What is a viewport?

The viewport refers to the part of the webpage that is visible in its window, and its dimensions are measured in CSS pixels. Do not confuse this with the physical resolution of the screen!

Here are some examples of viewport widths -

ViewportWidth (in CSS pixels)
Fully maximized browser window on a 27 inch monitor2993
Browser window occupying 35% of the screen on a 27 inch monitor1047
Fully maximized browser window on a 14 inch MacBook Pro1800
Browser window occupying 50% of the screen on a 14 inch MacBook Pro900
Samsung Galaxy S21's screen360

The trick

Below is the CSS I use to set the width of the central div that holds the content for this website -

max-width: min(max(480px, 50vw), 100vw);

The code above essentially follows 3 conditions:

  1. If 50% of the viewport's width > 480px, then use 50% of the viewport's width

    • This ensures that for large windows or screens like a 27 inch monitor, the content of the webpage is not extended and difficult to read like first image, but compact, in-focus and easy to read like the second one.
Text occupying 100% of a 2993px wide viewport.
Text occupying 100% of a 2993px wide viewport.
Text occupying 50% of a 2993px wide viewport. Centered, in-focus and easier to read.
Text occupying 50% of a 2993px wide viewport. Centered, in-focus and easier to read.
  1. If condition #1 is false and 100% of the viewport's width is < 480px, then set the width to 480px

    • For medium-sized windows or screens, this ensures that we are using somewhere between 60% to 100% of the viewport's width, so that our content is not too extended or too congested.
Text occupying 50% of a 585px wide viewport. Too cramped.
Text occupying 50% of a 585px wide viewport. Too cramped.
Text occupying 100% of a 585px wide viewport.
Text occupying 100% of a 585px wide viewport.
Text occupying 480px i.e. 82% of a 585px wide viewport.
Text occupying 480px i.e. 82% of a 585px wide viewport.
  1. If conditions #1 and #2 fail, then use 100% of the viewport's width
    • This allows the website to use all of the real-estate on a mobile screen.

Finally, below are some plots to drive home the message. Hope this was helpful!

Container width vs viewport width
Container width vs viewport width
% of viewport width utilized vs viewport width
% of viewport width utilized vs viewport width