kentcdodds
kentcdodds

Reputation: 29081

Write class definitions with stylus

I want to output something like this:

.margin-right-small {
  margin-right: 10px;
}

.margin-right-medium {
  margin-right: 15px;
}

.margin-right-large {
  margin-right: 20px;
}
/* same for top, bottom, and left */

Is it possible for me to do something to make this easier than this:

small = 10px
medium = 15px
large = 20px

.margin-right-small {
  margin-right: small;
}

.margin-right-medium {
  margin-right: medium;
}

.margin-right-large {
  margin-right: large;
}
/* same for top, bottom, and left */

Something like this pseudo code:

small = 10px
medium = 15px
large = 20px
sides = ['top', 'right', 'bottom', 'left']
sides.each(function(side) {
  .margin-[side]-small {
    margin-[side]: small;
  }

  .margin-[side]-medium {
    margin-[side]: medium;
  }

  .margin-[side]-large {
    margin-[side]: large;
  }
}
/* that would take care of all sides */

I'm a newbie with stylus. Is simplifying this possible? If not, I'm having a hard time seeing how stylus is better than regular css in this specific example...

Upvotes: 0

Views: 130

Answers (2)

Hauleth
Hauleth

Reputation: 23586

In Stylus you have interpolation and iteration. So after joining them together it should work (I don't know Stylus, so propably you need to do some small fixes):

for side in sides
  .margin-{side}-small
    margin-{side} small

Upvotes: 3

Deharlan
Deharlan

Reputation: 32

Creating something like this in CSS, it's impossible, but you can use PHP, and create a php file with html codes, you can. as in the example:

<?php $small = '15px'; ?>
<style>
.class {
   margin-right: <?php echo $small; ?>;
}
</style>

Remember you need to create this in a php file, and include in your <head> like this:

<?php include '\style.php'; // you are including the file style.php ?>

Upvotes: -1

Related Questions