将值从HTML传递到CSS [英] Pass a value from HTML to CSS

查看:658
本文介绍了将值从HTML传递到CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很感兴趣是否可以将值从html传递给css类? 像这样 示例:

I was interested whether can I pass value to the css class from the html? Like this Example:

<div class="mt(5)"> Some text </div>
style {
 .mt(@mpx) {
   margin-top: @mpx px;
 }
}

我听说在Less中可以这样

I've heard that such way was possible in Less

推荐答案

不,您想要的方式在CSS或其任何超集(如Less和其他)中都是不可能的.始终都是HTML,它使用来自CSS的值,而不是相反.因此,您将需要一些脚本来满足您的需求.

No, the way you want it is impossible in either CSS or any of its supersets (like Less and others). It's always HTML that uses values from CSS and not in opposite. Thus you'll need some scripting for what you need.

可以但是可以通过使用内联样式的自定义属性:

.c {color:  var(--c)}
.m {margin: var(--m)}

<div class="c" style="--c: blue" >Foo</div>
<div class="m" style="--m: 0 2em">Bar</div>
<div class="c" style="--c: green">Baz</div>

甚至是这样:

* {
    color:  var(--c);
    margin: var(--m);
    /* etc. */
}

<div style="--c: blue" >Foo</div>
<div style="--m: 0 2em">Bar</div>
<div style="--c: green">Baz</div>

但是该方法与普通香草方法的样式相同,即< .

But that method is no way different from styling by the plain vanilla method, i.e.:

<div style="color: blue"> 
... etc. 

这基本上是丑陋且不可维护的.

It is essentially same ugly and non-maintainable.

许多人试图通过生成数百个预定义的类(例如.mt-1.mt-2,... .mt-99等)来实现该目标(因为在CSS预处理器中这样做非常容易).但这是一个更丑陋的解决方案(我不会为您提供详细信息,因为这样做的细节.您将在其他地方阅读该内容,或者在几个项目之后学习一下自己).

Many people try to achieve the goal by generating hundreds of predefined classes like .mt-1, .mt-2, ... .mt-99 etc. (since it's extremely easy thing to do in a CSS-preprocessor). But it's even more ugly solution (I won't bother you with details on why it is so. You'll read about that elsewhere or learn yourself after a few projects).

这篇关于将值从HTML传递到CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆