Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional CSS rules with less, based on variable

Tags:

css

less

The variable can take percentage or px values, like:

@some-var: 50px; or @some-var: 46%;

How can I define a certain set of CSS rules if the value is in pixels, and a different set of rules if the values is in percentages?

Is there something like

if(isValueInPixels(@some-var)){

  // css rules here


}else{

  // other rules here
}

?

like image 249
Alex Avatar asked Sep 14 '12 13:09

Alex


People also ask

How do you write less in CSS?

Create a stylesheet with . less extension and link it in your document using the rel="stylesheet/less" attribute. You are all set and can compose styles within the . less .

What can be passed to a less mixin?

Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.


2 Answers

I think you can use something that they call Guarded Mixins.

Try something like this...

.mixin (@a) when (ispixel(@a)) {
 /* ... your pixel specific logic ... */
}
.mixin (@a) when (ispercentage(@a)) {
 /* ... your percentage specific logic ... */
}

.coolStuff {
 .mixin(50px);
 .mixin(50%);
}

See the Guarded Mixins at http://lesscss.org/

like image 153
Adam Spicer Avatar answered Oct 18 '22 00:10

Adam Spicer


As Adam Spicer noted the Guarded Mixins are your best solution. However, LESS now offers a solution to group multiple guards, which will allow this to be accomplished with a single mixin. http://lesscss.org/features/#css-guards-feature

For Example:

.mixin(@a){
  & when (ispixel(@a)){
    //logic
  }
  & when (ispercentage(@a)){
    //logic
  }
}

Usage:

selector{
  .mixin(50px);
  .mixin(46%);
}
like image 35
EoghanTadhg Avatar answered Oct 18 '22 01:10

EoghanTadhg