Home  >  Article  >  Web Front-end  >  Can SASS Mixin Values Be Dynamic CSS Properties?

Can SASS Mixin Values Be Dynamic CSS Properties?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 10:52:30899browse

Can SASS Mixin Values Be Dynamic CSS Properties?

Can SASS Mixin Values Be CSS Properties?

Problem:

Creating a universal margin/padding mixin, you've been unsuccessful due to an incorrect code structure:

[class*="shift"] {
  $sft-o: 10px;
  @mixin shift_stp($val) {
    &[class*="_sml"]{ $val: $sft-o; }
    &[class*="_mid"]{ $val: $sft-o * 2; }
    &[class*="_big"]{ $val: $sft-o * 3; }
  }
  &[class*="_m"]{
    @include shift_stp(margin);
  }
  &[class*="_p"]{
    @include shift_stp(padding);
  }
}

Solution:

To use variables as CSS property names in a mixin value, string interpolation is required, achieved using #{$var} syntax:

[class*="shift"] {
  $sft-o: 10px;
  @mixin shift_stp($val) {
    &[class*="_sml"]{ #{$val}: $sft-o; }
    &[class*="_mid"]{ #{$val}: $sft-o * 2; }
    &[class*="_big"]{ #{$val}: $sft-o * 3; }
  }
  &[class*="_m"]{
    @include shift_stp(margin);
  }
  &[class*="_p"]{
    @include shift_stp(padding);
  }
}

Note: Ensure selector specificity by re-evaluating the attribute selector structure.

The above is the detailed content of Can SASS Mixin Values Be Dynamic CSS Properties?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn