Skip to main content

How do I generate dynamic classes?

CSS • Asked by William Kennedy
Is there a way to generate dynamic classes with scss/sass? For example, in my HTML. I want to write 

div class='mt-10'></div>
div class='mt-7'></div>
div class='mt-3'></div>

This should create a div that has a margin-top of 10px, 7px, 3px and I imagine the CSS will look like this:

.mt-{x} {
  margin-top: x;
}

Any help appreciated?





Ya I was looking at that but then I found this cool library that accomplished what I wanted. 

https://github.com/digitaledgeit/sass-spacing

I'm play around with it some more and see if I can come up with a robust solution. 

I did something like this when I was working out the column widths once, maybe you could do similar.

$grid-columns : 16 !default;
$grid-gutter : 0% !default;
$column-width : 100 / $grid-columns;

// Lets calculate the column widths, outputs in %'s
@function grid-column-width($n) {
@return $column-width * $n - ($grid-gutter*($grid-columns - $n)/$grid-columns);
}

@for $n from 1 through $grid-columns {
%col-#{$n} {
width: grid-column-width($n);
}
}

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.