我编写了以下填充修饰符,这些修饰符在编译时应删除填充。
我有
.no-padding{
&--all{
padding:0!important;
}
&--top{
padding-top:0!important;
}
&--bottom{
padding-bottom:0!important;
}
&--left{
padding-left:0!important;
}
&--right{
padding-right:0!important;
}
}
这在css中有效,例如:<div class="no-padding--all">
消除了所有边距。但是我正在寻找一种进一步优化此方法的方法,因为我也有类似的重复边距。我还可以进一步在sass中优化此方法。 / p>
答案 0 :(得分:2)
除了其他答案,我将有另一种方法。
$directions: top, right, bottom, left;
$properties: padding, margin;
$directions: top, right, bottom, left;
$properties: padding, margin;
/* This loop will create the .x-all classes */
@each $property in $properties {
.no-#{$property}--all {
#{$property} : 0 !important;
}
}
/* This loop will create all the other direction specific classes */
@each $direction in $directions {
@each $property in $properties {
.no-#{$property}--#{$direction} {
#{$property}-#{$direction} : 0 !important;
}
}
}
答案 1 :(得分:0)
.no-padding{
padding: 0 !important;
&--top{
padding-top: 0 !important;
}
&--bottom{
padding-bottom: 0 !important;
}
&--left{
padding-left: 0 !important;
}
&--right{
padding-right: 0 !important;
}
}
这样,您可以直接使用.no-padding
代替.no-padding--all
。
您还可以简化修饰符的命名,例如使用一个字母代替--top, --right, --bottom, --left
到--t, --r, --b, --l
,否则其他所有操作都可以。
@mixin no-padding($dir){
@if $dir == 'top' {
padding-top: 0 !important;
}
@if $dir == 'right' {
padding-right: 0 !important;
}
@if $dir == 'bottom' {
padding-bottom: 0 !important;
}
@if $dir == 'left' {
padding-left: 0 !important;
}
@if $dir == 'all' {
padding: 0 !important;
}
}
像这样将其包含在您的班级中:
.no-padding{
@include no-padding(all);
&--top{
@include no-padding(top);
}
&--bottom{
@include no-padding(bottom);
}
&--left{
@include no-padding(left);
}
&--right{
@include no-padding(right);
}
}
请注意,您可以将此混入@include no-padding($dir)
与任何类一起使用。
答案 2 :(得分:0)
您可以使用mixin
@mixin no-padding(
$all: false,
$left: false,
$right: false,
$top: false,
$bottom: false,
) {
@if($all) {
padding: 0 !important;
}
@if($left) {
padding-left: 0 !important;
}
@if($right) {
padding-right: 0 !important;
}
@if($top) {
padding-top: 0 !important;
}
@if($bottom) {
padding-bottom: 0 !important;
}
}
用法:
.no-padding--all {
@include no-padding($all: true);
}
.no-padding--left {
@include no-padding($left: true);
}
.padding--left-only {
@include no-padding($top: true, $right: true, $bottom: true);
}
.no-padding--vertical {
@include no-padding($left: true, $right: true);
}
此外,这使您可以自由选择参数,并且可以编写灵活的类,因此不必在HTML中提供多个类名。 (例如:padding--left-only
,no-padding--vertical
)
您可以编写一个mixin来动态赋予属性(我不推荐)。
@mixin no-property(
$property,
$all: false,
$left: false,
$right: false,
$top: false,
$bottom: false,
) {
@if($all) {
#{$property}: 0 !important;
}
@if($left) {
#{$property}-left: 0 !important;
}
@if($right) {
#{$property}-right: 0 !important;
}
@if($top) {
#{$property}-top: 0 !important;
}
@if($bottom) {
#{$property}-bottom: 0 !important;
}
}
用法:
.no-padding--left {
@include no-property($property: 'padding', $left: true);
}
.no-margin--right {
@include no-property($property: 'margin', $right: true);
}