LESS - Using a variable on a CSS class

社会主义新天地 提交于 2019-12-11 07:04:45

问题


This is a bit of a long shot, but I wondered if its possible to set a number as part of class and based on that number use it to set the height of the CSS

HTML Example:

<div class="div-height-100"></div>

LESS Basic idea:

.div-height-@var{
    height: @height;
}

CSS Output:

.div-height-100 {
    height: 100px;
}

The idea of this is due to having multiple empty-chart-loader DIVs all of which are different heights, and will save setting up a different CSS class for each height.

Any help will be appreciated


回答1:


LESS is compiled into CSS so its values, after be processed, can't be modified by classes defined in HTML code.

In order to obtain a result similar to one that you're trying to obtain, you must create different CSS classes in advance.

.div-height-100 {
  height: 100px;
}
.div-height-200 {
  height: 200px;
}
.div-height-300 {
  height: 300px;
}
.div-height-400 {
  height: 400px;
}

This CSS can be automatically generated using the following LESS code, that use LOOPS construct (note also use of EXTRACT function). I'm assuming that you already know what are possible "height" values, and stored them in a LIST. You can simply add more values to list, in order to generate more CSS classes:

//Possible height values
.div-heights(100, 200, 300, 400);

.generate-heights-loop(@var; @possible-values) when (@var <= length(@possible-values)) 
{
  //Let's extract values in @var position from list @possible-values
  @height: extract(@possible-values, @var);

  .div-height-@{height} 
  {
    height: unit(@height,px);
  }

  .generate-heights-loop((@var + 1), @possible-values);
}

.div-heights(@possible-values...) 
{
  .generate-heights-loop(1, @possible-values);
}


来源:https://stackoverflow.com/questions/28068010/less-using-a-variable-on-a-css-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!