在 SASS 中使用类数组

  • 本文关键字:数组 SASS css sass
  • 更新时间 :
  • 英文 :


Using SASS/SCSS.我有以下几点:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}

这根本不可读。如何使用类数组重构它:

$full-page-classes: .sessions .registrations .home .posts.new

如果我理解你的意思正确,你可能想像这样使用数组

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';
@each $page-class in $full-page-classes {
body:not(#{$page-class}) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
}

输出:

body:not(.sessions) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
body:not(.registrations) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
body:not(.home) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
body:not(.posts.new) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}

你可以在萨斯迈斯特上试试


更新:

如果你想生成内联CSS,你可以试试这个:

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';
$temp: '';
@each $page-class in $full-page-classes {
$temp: $temp + ':not(#{$page-class})';
}
@each $item in $temp {
body#{$item} {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
}

输出:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
padding-top: 4.5rem;
padding-bottom: 7rem;
}

更新 2:

@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
$full-page-classes: ' .sessions, .registrations, .home, .posts.new,';
@each $x in str-replace(str-replace($full-page-classes, ' ', ':not('), ',', ')') {
body#{$x} {
padding-top: 4.5rem;
padding-bottom: 7rem;
}
}

参考:str-替换功能

最新更新