css - 基于引导网格断点为自定义类实现 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 的文章,但不能完全理解它
解决方案
不是在您的媒体查询中max-width
使用min-width
,而是说如果您的元素至少有这么宽,则将此属性应用于它。
此外,如果您使用 2 个循环,则所有w-40
,类都在, ... 类w-60
之前定义,而and类则优先于之前的类。w-sm-40
w-md-40
sm
md
同样,所有的xs
类都在类之前定义sm
,因此sm
类优先于类,xs
依此类推,md
直到lg
xl
//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;
}
}
推荐阅读
- android - 强制 Android WebView 在默认浏览器中打开外部链接
- c# - 验证使用仅初始化设置器初始化的 C# 对象
- javascript - 如何将现有 JSON 中的对象添加到 Node JS 中的空对象
- javascript - 在本地存储上编辑、清除和设置到期时间/日期
- reactjs - Reactjs - How to re-direct to default home page
- html - 使用 CSS 单击其他卡片时将卡片翻转回来
- bash - 无法在通过 Atlantis(Terraform Pull Request Automation)工具运行的 terraform local-exec 配置程序中设置环境变量
- networking - 我们如何配置“网络活动受限的 Pod”并节省计费?
- spring - 在 Spring Boot 中实现 @LocalPort 等功能
- javascript - 像 ComponentDidUpdate 一样使用 useEffect