Matthew
Matthew

Reputation: 611

Any way to get breakpoint-specific width classes?

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?

Upvotes: 23

Views: 16320

Answers (5)

Keith Turkowski
Keith Turkowski

Reputation: 811

Without modifying the CSS, you can accomplish this via row / col:

<div class="row">
  <div class="col-3"></div>
  <div class="col-lg-6 col-12">
    Content Goes Here
  </div>
  <div class="col-3"></div>
</div>

Upvotes: 1

David Fleury
David Fleury

Reputation: 94

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";

Upvotes: 4

user1501025
user1501025

Reputation: 81

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.

Upvotes: 8

Duncan Jones
Duncan Jones

Reputation: 69339

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.

Upvotes: 9

Matthew
Matthew

Reputation: 611

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;}
    }
  }
}

Upvotes: 18

Related Questions