我使用 mixins 找到了解决此问题的逻辑。
我创建了一个 Mixin,它接受所有作为列表传递的 参数,因此声明以 ... 结尾
此解决方案还涵盖了可选的 CSS 属性,这些属性可能未包含在所有类中,但大部分包含在其中。
styles.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 代码。
希望这能解决您的问题。欢迎提出建议/意见以改进此逻辑。