stylus / stylus

Expressive, robust, feature-rich CSS language built for nodejs
https://stylus-lang.com
MIT License
11.2k stars 1.12k forks source link

[RESEARCH] How to get comma-separated selectors after iteration? #1027

Closed sergeevabc closed 11 years ago

sergeevabc commented 11 years ago

Dear Stylus community,

I'm in the middle of converting an old project (not DRY, not OOCSS, no framework, etc) to modern guidelines. For me it's easy to learn new tricks by going step by step, not starting from scratch. That's why I'd like to see how early CSS practices work in a new environment (e.g. with Stylus) before making global changes.

It is cool to be able to turn

for x in 1..24
    .push-{x}
        position relative
        float    right
        margin   0 (x * -40px) 24px (x * 40px)

into

...
}
.push-23 {
  position: relative;
  float: right;
  margin: 0 -920px 24px 920px;
}
.push-24 {
...

But I don't like to have position: relative; and float: right repeated 24 times! Some of you would say "c'mmon, gzip will take care of redundancy", but I still prefer to rely on brainwork.

Could you be so kind and tell me how to command Stylus to optimize our overhead as follows?

...
.push-1,.push-2,...,.push-24 {
    position: relative;
    float: right;
}

Thank you in advance.

Warm regards from Russia, Alexander.

sergeevabc commented 11 years ago

bump

cspotcode commented 11 years ago

You can pull those common stylus into a dummy selector and then @extend that dummy selector.

For example:

.push-common
    position relative
    float right

for x in 1..24
    .push-{x}
        @extend .push-common
        margin 0 (x * -40px) 24px (x * 40px)

Will compile into:

.push-common,
.push-1,
.push-2,
.push-3,
// .....
.push-24 {
  position: relative;
  float: right;
}
.push-1 {
  margin: 0 -40px 24px 40px;
}
.push-2 {
  margin: 0 -80px 24px 80px;
}
.push-3 {
  margin: 0 -120px 24px 120px;
}
// .....

The only downside is that you have a .push-common selector in your CSS, but I doubt that will break anything. You can use a naming convention to distinguish between real selectors and so-called "hidden selectors."

kizu commented 11 years ago

With the new version (0.33) of Stylus we have placeholder selectors, so you can use the @cspotcode's solution, replacing .push-common with $push-common and you'd get your clean code :)