【问题标题】:Can I pass a parameter to a CSS class?我可以将参数传递给 CSS 类吗?
【发布时间】:2021-10-27 23:52:58
【问题描述】:

假设我有一个有很多属性的类,我想使用 该类在另一部分中,但一个属性值不同。

我们可以这样做吗?

请看我的例子:

.class-test {
       position: relative;
       display: inline-block;
        @include border-radius(3px / 3px 3px 3px 4px);
        background-color: GREEN;
       width: 266px; // This property should be dynamic..    
      .select-something {
            display: inline-block;
            font-size: 14px;
       }
       ....
        and much more properties..
       ....
}

所以我在两个不同的地方使用这个类 其中一个 width 应该是 266px 在另一个 width 应该是 120px;

  <div class="class-test">
       .....
       // here width should be 266px
  </div>

  <div class="class-test">
       .....
       // here width should be 120px
  </div>

当然我可以创建两个不同宽度的不同类 但它会以大量重复代码

结束

【问题讨论】:

  • 为什么不在第二个 divclass="class-test small",然后在 CSS .class-test.small { width: 120px; ...... 中?

标签: html css sass


【解决方案1】:

您可以从类中删除该属性

然后再使用两个类。例如。

.width-1 {
width: 266px;
}

.width-2 {
width: 120px;
}

。 . .

并在每个元素中包含两个类

<div class="class-test width-1">
       .....
       // here width should be 266px
</div>

<div class="class-test width-2">
     .....
     // here width should be 120px
</div>

【讨论】:

    【解决方案2】:

    试试这个

    <div class="class-test">
           .....
           // here width should be 266px
      </div>
    
      <div class="class-test testclass" >
           .....
           // here width should be 120px
      </div>
    

    CSS

    .class-test.testclass 
    { 
    width: 120px;
    }
    

    小提琴:https://jsfiddle.net/1h1w8202/

    【讨论】:

      【解决方案3】:

      我猜你可以使用这个技巧:

      <div class="class-test">
             .....
             // here width should be 266px
        </div>
      
        <div class="class-test" style="width:120px">
             .....
             // here width should be 120px
        </div>
      

      Demo

      【讨论】:

        【解决方案4】:

        这似乎让我可以将视频放置在页面上的任何位置。

        <!DOCTYPE html> 
        <html> 
        
        <head>
        <style>
        div.relative {
            position: relative;
            z-index: -1;
        }
        </style>
        </head>
        
        <body> 
        
        <div class="relative" style='left:20px; top:30px'>
            <video width="400"  autoplay loop>
              <source src="dinoheads.mp4" type="video/mp4">
              Your browser does not support HTML5 video.
            </video>
        </div>
        
        <p>
        
        </p>
        
        </body> 
        </html>
        

        【讨论】:

          猜你喜欢
          • 2013-11-18
          • 1970-01-01
          • 1970-01-01
          • 2013-01-05
          • 1970-01-01
          • 1970-01-01
          • 2013-06-11
          • 1970-01-01
          • 2015-10-26
          相关资源
          最近更新 更多