cssbootstrap-4sassbootstrap-grid

Calculate with Bootstrap container width in Sass


I want to add a 50% container to every breakpoint.

For example: The witdh of .container is 1140px in the xl breakpoint. So I want to do something like this:

.is-style-container-50 {
    max-width: calc($container-max-widths / 2);
}

I found the variable $container-max-widths in the docs. There are the breakpoints in it like this:

$container-max-widths: (
  sm: 540px,
  md: 720px,
  lg: 960px,
  xl: 1140px
);

The problem is, that I get an error message like this:

Error: (sm: 540px, md: 720px, lg: 960px, xl: 1140px) isn't a valid CSS value.

Is there any other way to use the container width for calculations? Or do I have to use fixed values?


Solution

  • $container-max-widths is a list of values mapped to the keys (sm,md,lg,xl). You need to get a value from the xl key of $container-max-widths.

    Example for xl you need this:

    .is-style-container-50 {
        max-width: map-get($container-max-widths , xl) / 2;
    }
    

    To use all the breakpoints you need to cycle trough all the list:

    @each $size-name in map-keys($container-max-widths){
        $size-value: map-get($container-max-widths , $size-name);
        .is-style-container-50 {
            @include media-breakpoint-up($size-name){
                max-width: $size-value / 2;
            }
        }
    }
    

    You can also build another list with 50% of values and use it with the Bootstrap mixin for add max-widths to his containers make-container-max-widths($max-widths: $container-max-widths, $breakpoints: $grid-breakpoints):

    $container-mid-max-widths: (
      sm: #{map-get($container-max-widths, sm)*0.5},
      md: #{map-get($container-max-widths, md)*0.5},
      lg: #{map-get($container-max-widths, lg)*0.5},
      xl: #{map-get($container-max-widths, xl)*0.5}
    );
    
    .mid-container {
        // Using Bootstrap Mixin: make-container-max-widths($max-widths: $container-max-widths, $breakpoints: $grid-breakpoints)
        @include make-container-max-widths( $container-mid-max-widths , $grid-breakpoints );
    }