html - SASS:从 mixin 或函数返回一组不同的 CSS 属性
问题描述
我的模板中几乎没有 DIV,它们具有共同的属性,但每个属性的值不同。下面列出了这些
- 字母间距
- 文本转换
- 字体系列
- 字体粗细
- 字体大小
- 颜色
Mixins 仅接受基于属性的参数,并且函数返回单个值。
我想知道 SASS/SCSS 是否有任何实用程序来处理相同的问题。我应该将这些值作为参数传递给 SASS,它应该返回所有使用参数更新的 CSS 属性。
解决方案
我使用mixins找到了这个问题的逻辑。
我创建了一个 Mixin,它接受作为列表传递的所有参数,因此声明以 ... 这个解决方案还包括可选的 CSS 属性,这些属性可能不包含在所有类中,但大多数类中。
样式.scss
.blog-content {
// for .destination
@include text-properties("destination", "EpicRide", normal, 65px, $standard-black, none, 2.8px, '', '');
// for .intro-title
@include text-properties("intro-title", "Montserrat", 500, 14px, $standard-black, uppercase, 2.8px, 5px 5% 0, '');
// for .place
@include text-properties("place", "Montserrat", 500, 14px, $standard-black, uppercase, 2.8px, inherit, '');
// for .description
@include text-properties("description", "Lora", 400, 16px, $standard-light, none, 0, 0 5%, 20px);
}
_variables.scss
@mixin text-properties($args... ) { // args has a list of arguments
$class: nth($args, 1); // nth is used to extract 'nth' argument's value
$font-family: nth($args, 2);
$font-weight: nth($args, 3);
$font-size: nth($args, 4);
$color: nth($args, 5);
$text-transform: nth($args, 6);
$letter-spacing: nth($args, 7);
$padding: nth($args, 8);
$margin-top: nth($args, 9);
.#{$class} { // create class dynamically. Mention the variable name inside #{} to fetch it's value
font-family: $font-family;
font-weight: $font-weight;
font-size: $font-size;
color: $color;
text-transform: $text-transform;
letter-spacing: $letter-spacing;
@if $padding != '' { // condition to ensure property is added only if valid param is passed.
padding: $padding;
}
@if $margin-top != '' {
margin-top: $margin-top;
}
}
}
结果 CSS
.blog-content .destination {
font-family: "EpicRide";
font-weight: normal;
font-size: 65px;
color: rgba(0, 0, 0, 0.9);
text-transform: none;
letter-spacing: 2.8px;
}
.blog-content .intro-title {
font-family: "Montserrat";
font-weight: 500;
font-size: 14px;
color: rgba(0, 0, 0, 0.9);
text-transform: uppercase;
letter-spacing: 2.8px;
padding: 5px 5% 0;
}
.blog-content .place {
font-family: "Montserrat";
font-weight: 500;
font-size: 14px;
color: rgba(0, 0, 0, 0.9);
text-transform: uppercase;
letter-spacing: 2.8px;
padding: inherit;
}
.blog-content .description {
font-family: "Lora";
font-weight: 400;
font-size: 16px;
color: rgb(var(--LightColorRGB));
text-transform: none;
letter-spacing: 0;
padding: 0 5%;
margin-top: 20px;
}
但是,此解决方案有一个限制,CSS 属性数量的增加会增加 mixin 代码。
我希望这能解决你的问题。欢迎提出建议/意见以改进此逻辑。
推荐阅读
- focus - 如何触发自动对焦并仍然在 camera2 API 中保持当前的 ISO 和速度?
- java - 在java中操作文件
- reactjs - 如何解耦路由器和导航栏,使导航栏组件不包含组件
- list - groovy 是否有内置的方式来遍历/转换数据结构?
- netbeans-8 - Netbeans 8.0.2 更新后无法启动
- ubuntu - 运行 Airflow 时无法访问 localhost
- java - 尝试使用具有有效购买令牌的 Java Google Play Developer API v3 检索应用内购买信息时出现错误请求(无效值)
- javascript - SQLite (sql.js) 上的 DELETE 语句什么都不做
- csv - 在 java 中解析大型 CSV 文件的最快和最有效的方法
- node.js - 在 Express Web 应用程序中休息全面服务