'Bootstrap 5 grid, how to customize the grid gutters at different breakpoints (not using utility classes)?

How can I customize Bootstrap 5 to have different grid gutters at different breakpoints? I don't want to use the grid spacing utility classes because those would be hard coded all over the place in markup and a pain to change.

It looks like Bootstrap 5 has this variable as the default gutter width across the board:

$grid-gutter-width: 1.5rem;

What I want is something like this (the values are just made up to illustrate the idea):

$grid-gutter-width-sm: 1rem;
$grid-gutter-width-md: 1.5rem;
$grid-gutter-width-lg: 2rem;
$grid-gutter-width-xl: 2.5rem;


Solution 1:[1]

This is tricky because the gutter is used to build all the container*, row and col*. You can make a custom map with the gutter widths for each breakpoint, and then iterate the map to re-build the grid at each breakpoint:

@import "functions";
@import "variables";
@import "mixins";

$custom-gutter-widths: (
  sm: 1rem,
  md: 1.5rem,
  lg: 2rem,
  xl: 2.5rem,
  xxl: 3rem,
);

@import "bootstrap";

@each $breakpoint, $gutterwidth in $custom-gutter-widths {
    $container-padding-x: $gutterwidth*.5;
    $grid-gutter-width: $gutterwidth;
    @include media-breakpoint-up($breakpoint, $grid-breakpoints) {
        .container,
        .container-fluid {
            @include make-container();
        }
        
        .row {
            @include make-row();
            
            > * {
              @include make-col-ready();
            }
        }
        @include make-grid-columns();
        
    }
}

Bootstrap SASS on Codeply

Note: This is making a lot of extra CSS!

Solution 2:[2]

I think adding breakpoint in body to overwrite --bs-gutter-x should be enough:

body {
  @include media-breakpoint-down(sm) {
    --bs-gutter-x: 1rem;
  }
  @include media-breakpoint-down(md) {
    --bs-gutter-x: 1.5rem;
  }
  @include media-breakpoint-down(lg) {
    --bs-gutter-x: 2rem;
  }
  @include media-breakpoint-down(xl) {
    --bs-gutter-x: 2.5rem;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Reorx