首页 > 解决方案 > 基于引导网格断点为自定义类实现 css 特异性

问题描述

我正在尝试创建自己的宽度类,以使用引导程序网格断点的引导程序。这些类被命名为 likew-10, w-20并且宽度分别为 10% 和 20%,或者w-sm-10 w-sm-20在宽度大于sm(576px) 的屏幕上命名为 like 并且宽度为 10% 和 20%,但它们的移动设备上的初始宽度。

使用这个片段,我已经能够创建具有这种效果的类。

@import 'node_modules/bootstrap/scss/bootstrap.scss';

$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};   
  }
  @each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
    .w-#{$bp-name}-#{$i} {  //names like w-md-40
      width: #{"#{$i}%"};
    }
    @media screen and (max-width: $bp-pixels) {       //Remove the width at the corresponding screen widths
      .w-#{$bp-name}-#{$i} {
        width: initial;
      }
    }
  }
  $i : $i + 10;
}

只要我的元素只有其中一个类,此解决方案就可以工作,但在分配 2 个或更多时会中断,因为没有为这些类中的任何一个分配优先级

前任。此类应在比 lg 宽的屏幕上具有 50% 的宽度,在比 sm 宽的屏幕上具有 70% 的宽度,在所有小于 sm 的屏幕上具有 90% 的宽度,但这个宽度的 div 将始终为 90% .

<div class='w-lg-50 w-sm-70 w-90'></div>

我读过一些关于css-specificity 的文章,但不能完全理解它

标签: csstwitter-bootstrapsassbootstrap-4

解决方案


不是在您的媒体查询中max-width使用min-width,而是说如果您的元素至少有这么宽,则将此属性应用于它。

此外,如果您使用 2 个循环,则所有w-40,类都在, ... 类w-60之前定义,而and类则优先于之前的类。w-sm-40w-md-40smmd

同样,所有的xs类都在类之前定义sm,因此sm类优先于类,xs依此类推,md直到lgxl

//Creates width classes like w-40, w-60 ...
$i : 10;
@while $i <= 90 {
  .w-#{$i} {              //names like w-40, w-60
    width: #{"#{$i}%"};   
  }
  $i : $i + 10;
}

@each $bp-name, $bp-pixels in $grid-breakpoints {   //looping through xs, sm, md, lg, xl and their pixel values
  $i : 10;
  @while $i <= 90 {
    @media (min-width: $bp-pixels){ //only works if the screen is wider than this
      .w-#{$bp-name}-#{$i} {  //names like w-md-40
          width: #{"#{$i}%"};
      }
    }
    $i : $i + 10;
  }
}

推荐阅读