My goal is to create custom width classes that leverage Bootstrap's grid breakpoints. These classes, such as w-10, w-20
, would represent widths of 10% and 20% respectively. Alternatively, classes like w-sm-10, w-sm-20
would specify widths of 10% & 20% on screens wider than the 'sm' breakpoint (576px), falling back to their default width on mobile.
Through this code snippet, I have successfully generated classes with this behavior:
@import 'node_modules/bootstrap/scss/bootstrap.scss';
$i : 10;
@while $i <= 90 {
.w-#{$i} {
width: #{"#{$i}%"};
}
@each $bp-name, $bp-pixels in $grid-breakpoints {
.w-#{$bp-name}-#{$i} {
width: #{"#{$i}%"};
}
@media screen and (max-width: $bp-pixels) {
.w-#{$bp-name}-#{$i} {
width: initial;
}
}
}
$i : $i + 10;
}
While this approach works when applying a single class to elements, it breaks down when multiple classes are combined due to lack of specificity:
For example, the class assignment
<div class='w-lg-50 w-sm-70 w-90'></div>
should result in widths of 50% for lg screens, 70% for sm screens, and 90% otherwise. However, the resulting width remains fixed at 90% regardless of screen size.
I've attempted to understand CSS specificity through resources like W3Schools, but it still eludes me.