Pass a value from HTML to CSS

亡梦爱人 提交于 2019-12-11 14:50:20

问题


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

I've heard that such way was possible in Less


回答1:


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.

You can however pass values from HTML to CSS via Custom Properties using inline styles:

.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>

Or even like this:

* {
    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.


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).




回答2:


Here is a way of doing that without the use of LESS.

You can use CSS variables:

// When clicking on the first div, padding is gonna grow up.
document.getElementById("div1").onclick = function(){
  var nb = parseInt(this.style.getPropertyValue("--nb"));
  this.style.setProperty("--nb", nb + 1);
}
.bg_colored {
  background-color: var(--bg);
}

div {
  padding: calc(var(--nb)*5px);
}
<div id="div1" class="bg_colored" style="--bg: yellow; --nb: 1;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="bg_colored" style="--bg: #f66; --nb: 2;">Etiam semper diam at erat pulvinar, at pulvinar felis blandit.</div>

In my snippet, the CSS variables are declared in the style attribute of the HTML elements.
Note that the variable names must begin with -- and are case sensitive.
Then, the CSS uses these variables to apply the correct styles.

These variables values are applied to the element and its children.
To use it globally, you can declare it on the body tag.

Here is a link with some examples: https://www.w3schools.com/css/css3_variables.asp



来源:https://stackoverflow.com/questions/50037400/pass-a-value-from-html-to-css

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