0

I am looking at less.js, mixin looks like the way touching the variable in css but i am not sure if my problem is solvable using less.js.

I want to make some class with parameter, e.g. with the format

marginTop-10 or marginTop(15)

10,15 are some numbers which i can change to specify the margin top pixel, basically these numbers can be any number.and i will use these class in my paragraph class such as

<p class="marginTop(some number)">css help</p>

How can i make this happen?

onegun
  • 803
  • 1
  • 10
  • 27
  • 1
    The nature in which you are trying to call or reference the class via mixin 'class="marginTop(some number)"' is not quite semantically accurate and would result in invalid classes,css and html. So I'd suggest instead of using javascript to set the class based on a condition maybe and not call a mixin from the markup. But I'm also assuming your using this as a pre-processor. Also here are other references as well - http://stackoverflow.com/questions/10280567/how-to-set-the-css-class-name-dynamically-in-lesscss http://stackoverflow.com/questions/19602812/less-mixin-a-variable-class-name – Frankie Loscavio Nov 24 '14 at 04:03
  • 1
    You don't need CSS or Less for this kind of stuff at all. There's plain vanilla HTML style attribute: `

    non-css help

    `.
    – seven-phases-max Nov 24 '14 at 08:03
  • Duplicate of [Can less.js read class names and parameters from HTML?](https://stackoverflow.com/questions/17104746/can-less-js-read-class-names-and-parameters-from-html) – seven-phases-max Nov 06 '17 at 11:25

1 Answers1

0

You should first write your Less file, for instance as follows:

.marginTop(@topMargin) {
margin-top: @topMargin;
}

p.marginTop-10 {
.marginTop(10px); 
}

p.marginTop-15 {
.marginTop(15px); 
}

The preceding Less code will compile into the following CSS code:

p.marginTop-10 {
  margin-top: 10px;
}
p.marginTop-15 {
  margin-top: 15px;
}

After that you can use in your HTML:

<p class="marginTop-10">css help</p>
<p class="marginTop-15">css help</p>

Notice that you can also compile a list of classes dynamically, see also: LESS loops used to generate column classes in twitter - How do they work?

Doing that you could write the the following Less code:

@margins: 10 20 50;

.marginTop(@i: 1) when (@i <= length(@margins)) {
.marginTop(@i + 1);
@margin-top: extract(@margins,@i);
.marginTop-@{margin-top} {
    margin-top:unit(@margin-top,px);
    }
}

.marginTop();

outputs:

.marginTop-50 {
  margin-top: 50px;
}
.marginTop-20 {
  margin-top: 20px;
}
.marginTop-10 {
  margin-top: 10px;
}
Community
  • 1
  • 1
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224