Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate CSS content with a SASS for loop

Tags:

css

for-loop

sass

I'm trying to create a SASS mixin that would operate like this:

@include custom-horiz-sep(7);

which would output CSS:

content: "xxxxxxx";

(7 pre-defined characters)

How would I use a 'for' loop in SASS to create the value for the "content" property?

like image 681
protohominid Avatar asked Jan 27 '13 16:01

protohominid


People also ask

Can we use for loop in SCSS?

Sass has several loop options, much like other programming languages. They include the @for loop, @each loop and @while loop. These loops are an incredibly powerful tool for generating CSS code because you can defer code generation into an iterable task.

Can I use for loop in CSS?

While CSS doesn't have loop structures, it does provide a counter() that you can increment based on any number of DOM-related conditions, and use in generated content. Sadly it can't be used outside the content property (yet), so our background-colors are not applied: HTML.

What is @each in SCSS?

The @each rule makes it easy to emit styles or evaluate code for each element of a list or each pair in a map. It's great for repetitive styles that only have a few variations between them. It's usually written @each <variable> in <expression> { ... } , where the expression returns a list.

What is the difference between SCSS and sass?

SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax.


1 Answers

With bookcasey and cimmanon's help, here's what seems to work great:

@mixin custom-horiz-sep($num) {
  $chr: "x";
  $content: $chr;
  @for $i from 0 to $num {
      $content: $content + $chr;
  }
  content: "#{$content}";
}

h1:before {
  @include custom-horiz-sep(25);
}

http://codepen.io/Protohominid/pen/rgzKF

like image 74
protohominid Avatar answered Nov 12 '22 01:11

protohominid