14

Bootstrap 4 includes the width classes:

w-25
w-50
w-75
w-100

I want to specify widths only for certain breakpoints and above; e.g., "w-md-25", etc.

Is it possible to add such classes in the SCSS files, or otherwise get this functionality?

Matthew
  • 521
  • 3
  • 13

4 Answers4

18

Got it figured out with Blazemonger's help. I added this to my custom.scss file, recompiled, and it worked beautifully:

@each $breakpoint in map-keys($grid-breakpoints) {
  @each $size, $length in $sizes {
    @include media-breakpoint-up($breakpoint) {
      .w-#{$breakpoint}-#{$size} {width: $length !important;}
    }
  }
}
Matthew
  • 521
  • 3
  • 13
  • 4
    I had to add this for your code to work $sizes: ( 25: 25%, 50: 50%, 75: 75%, 100: 100%, ); But it worked, thanks! – Barrard Feb 09 '22 at 07:27
8

In the 'ugly as sin' solution category, if you don't want to play with SCSS you can do things like:

<!-- Show at 100% width on xs devices. Hide (d-sm-none) on sm and above -->
<element class="w-100 d-sm-none">

<!-- Hide on xs devices. Show normally on sm and above -->
<element class="d-none d-sm-flex">

Depending upon the complexity of what you are trying to achieve, this can be a workaround. See https://getbootstrap.com/docs/4.3/utilities/display/#hiding-elements for more detail on hiding selectively.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
6

So I did found another proper solution. You will have to override the utilities.scss with your own.

Just add after the import of the utilities.scss the snippet below (Docs for Bootstrap API). You can define even another values (I did add 33 and 66):

$utilities: map-merge(
  $utilities,
  (
    'width': (
      property: width,
      class: w,
      responsive: true,
      values: (
        25: 25%,
        33: 33%,
        50: 50%,
        66: 66%,
        75: 75%,
        100: 100%,
        auto: auto,
      ),
    ),
  )
);

The trick for the breakpoints is the addition of responsive: true, which will add those breakpoints prefixes later on in utilities/api.

user1501025
  • 61
  • 1
  • 2
2

Using bootstrap 5.2, same as user1501025, but I use override to make it works.

$utilities: (
  'width': (
    property: width,
    class: w,
    responsive: true,
    values: (
      25: 25%,
      33: 33%,
      50: 50%,
      66: 66%,
      75: 75%,
      100: 100%,
      auto: auto,
    ),
  )
);

@import "../../node_modules/bootstrap/scss/bootstrap.scss";
Eric Aya
  • 69,473
  • 35
  • 181
  • 253