我有这个HTML代码:
<div data-width="70"></div>
Run Code Online (Sandbox Code Playgroud)
我想在CSS中设置它的宽度等于data-width属性的值,例如:
div {
width: [data-width];
}
Run Code Online (Sandbox Code Playgroud)
我看到这是在某个地方完成的,但我记不住了.谢谢.
Ama*_*yla 41
这就是我要找的东西:
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
问题是即使是某些主流浏览器也不支持它,在这种情况下是Chrome.
Vik*_*dke 14
您不能将数据属性值直接传递给没有伪类型内容的css.相反,你可以这样做.. 检查这个问题
<div data-width="a"></div><br>
<div data-width="b"></div><br>
<div data-width="c"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
div[data-width="a"] {
background-color: gray;
height: 10px;
width:70px;
}
div[data-width="b"] {
background-color: gray;
height: 10px;
width:80px;
}
div[data-width="c"] {
background-color: gray;
height: 10px;
width:90px;
}
Run Code Online (Sandbox Code Playgroud)
ozg*_*zer 11
另一种方法是使用CSS 自定义属性和样式元素将值从 HTML 传递到 CSS。
div {
width: var(--width);
height: var(--height);
background-color: var(--backgroundColor);
}Run Code Online (Sandbox Code Playgroud)
<div
style="
--width: 50px;
--height: 25px;
--backgroundColor: #ccc;
"
></div>
<div
style="
--width: 100px;
--height: 50px;
--backgroundColor: #aaa;
"
></div>Run Code Online (Sandbox Code Playgroud)
内联CSS变量几乎与声明的数据属性,它们被广泛的支持,现在,在对比的attr()。看一下这个:
var elem = document.getElementById("demo");
var jsVar = elem.style.getPropertyValue("--my-var");
function next() {
jsVar = jsVar % 5 + 1; // loop 1..5
elem.style.setProperty("--my-var", jsVar);
}Run Code Online (Sandbox Code Playgroud)
.d1 {
width: calc( var(--my-var) * 100px );
background-color: orange;
}
.d2 {
column-count: var(--my-var);
}Run Code Online (Sandbox Code Playgroud)
<button onclick="next()">Increase var</button>
<div id="demo" style="--my-var: 2">
<div class="d1">CustomWidth</div>
<div class="d2">custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number</div>
</div>Run Code Online (Sandbox Code Playgroud)