Sass 'if' statement based on existing class

I am new to Sass and would like to use an if statement to find an existing class in an element to generate the appropriate css.

My installation has a large number of Javascript-generated images that are assigned a unique identifier, as well as a β€œpicture” class and a randomly assigned class from the top, right, bottom or left.

I also use a random function for Sass (here: https://gist.github.com/chriseppstein/1561650 ) and would like a different value to be assigned to each identifier, so that each element is in random order.

My SCSS has the following, which positions the images based on which class was assigned:

@for $i from 0 through $number-of-pictures { #picture-#{$i}{ &.top { left: random($stage-width); } &.right { top: random($stage-height); } &.bottom { left: random($stage-width); } &.left { top: random($stage-height); } } } 

This works well, but creates a ton of unused ad units. For example, # picture-38 was assigned the class ".top", so all I need is the first block of the declaration, but CSS exports all the parameters:

 #picture-38.top { left: 38px; //This is a random number that is different for each ID. } #picture-38.right { top: 28px; } #picture-38.bottom { left: 12px; } #picture-38.left { top: 47px; } 

I need an if statement that determines if an element has a class before parsing css. Sort of:

 @if "#picture-#{$i} has class $class-top" { &.top { left: random($stage-width); } } 

Any ideas?

+6
source share
2 answers

Answer: you cannot do this with SASS / SCSS.

You are trying to detect class ownership / assignment for a DOM element.

The way to interact with DOM elements is JavaScript

What you need to do is use JavaScript to determine if "picture-x #" has a class "class-top" and then set the random value to top .

eg.

 var picture = document.GetElementById('picture-1'); var pic_class = picture.className if(pic_class.indexOf('class-top') != -1) { /*Returns a random number between 1 and 100*/ picture.style.top = Math.floor((Math.random()*100)+1) + 'px'; } 

Sidenote: top requires a unit of measure (e.g. px ), therefore + 'px'

+3
source

Now the bit is old, but I have been working on something similar lately - here I use an array to scroll through different classes of buttons and add styles accordingly. Keep in mind that in the code snippet there are variables that are not declared.

 $buttonSizes: large-buttons, medium-buttons, small-buttons; @each $buttonSizesItem in $buttonSizes { %#{nth($buttonSizesItem, 1)}{ @if (nth($buttonSizesItem, 1))== large-buttons{ @include font-size(2); @include rounded(6); padding: 8px 15px; } @if (nth($buttonSizesItem, 1))== medium-buttons{ @include font-size(1.8); @include rounded(5); padding: 4px 12px; &.button-loading { &:before{ top: 2px; } } } @if (nth($buttonSizesItem, 1)) == small-buttons{ @include font-size(1.6); @include rounded(4); padding: 4px 10px; &.button-loading { &:before{ top: 0; } } } } } 
0
source

All Articles