且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

较少-在CSS类上使用变量

更新时间:2023-01-27 15:17:57

LESS被编译成CSS,因此其值在经过处理后不能被HTML代码中定义的类修改.

要获得与尝试获得的结果相似的结果,必须预先创建不同的CSS类.

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

可以使用以下LESS代码自动生成此CSS,该代码使用 LOOPS 构造(请注意还使用 EXTRACT 函数).我假设您已经知道什么是可能的高度"值,并将它们存储在LIST中.您可以简单地在列表中添加更多值,以生成更多CSS类:

//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);
}

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

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);
}