Search⌘ K

Responsive Spacing

Explore how to apply responsive spacing in CSS layouts by using padding, margin, and gap properties with functions like clamp() and min() to create flexible, content-relative designs. Understand how these techniques improve adaptability without relying on media queries, ensuring better alignment and accessibility across devices.

Spacing between and around elements can quite literally make or break a layout. Over the years, popular frameworks have provided quite strict spacing scales based on pixels and bound to viewport media queries.

Conventional method of scaling layouts

The following code is an example of spacing that’s bound to pixels and the viewport:

NAME_
CSS
.pt-1 { padding-top: 8px; }
.pt-2 { padding-top: 16px; }
.pt-3 { padding-top: 24px; }
/* "Medium (md)" breakpoint */
@media (min-width: 768px) {
.pt-md-1 { padding-top: 8px; }
.pt-md-2 { padding-top: 16px; }
.pt-md-3 { padding-top: 24px; } }
/* "Large (lg)" breakpoint */
@media (min-width: 1024px) {
.pt-lg-1 { padding-top: 8px; }
.pt-lg-2 { padding-top: 16px; }
.pt-lg-3 { padding-top: 24px; } }

This example application of those classes assumes we want to increase space for larger viewports, which then requires multiple classes to change the padding based on the available viewport space:

HTML
<div class="pt-1 pt-md-2 pt-lg-3">

While this convention is still a valid method, we can do better by leveraging more dynamic units that are also more localized to content sizes.

Properties used for spacing

Three properties are used for applying spacing around and between elements:

  • padding: This is used for spacing for an individual element’s box.

  • margin: This is used for spacing between elements.

  • ...