CSS - 使用数据属性添加颜色 - attr(data-color color)

新手上路,请多包涵

我试图在我的 css 中为具有数据属性的不同元素添加颜色,但不起作用…

我遵循以下说明:

attr() 函数:从已编辑文档中收集的属性值。

W3C

HTML

 <table>
    <tr>
        <td>
            <span class="bgborder" data-color="#e7663f"></span>
            <i class="fa fa-copy"></i>
        </td>
        <td>
            <span>Blaablaaablaaa</span>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td>
            <span class="bgborder" data-color="#77c385"></span>
            <i class="fa fa-upload fa-fw"></i>
        </td>
        <td>
            <span>Blablaablaaa</span>
        </td>
    </tr>
</table>

CSS

 .bgborder {
    display: block;
    width: 5px;
    height: 100%;
    position: absolute;
    top: 0;
    background-color: attr(data-color color);
}

什么都没有出现…我说得对吗?

在我的 chrome 检查器中,我有这个:

 background-color: attr(data-color color);
/!\ Invalid property value

我不明白为什么…???

谢谢你的帮助 :)

原文由 Zagloo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

阅读文档总是一个好主意: https ://developer.mozilla.org/en/docs/Web/CSS/attr

支持表截图

惊喜!如果没有任何支持,那么它将无法工作;)

备选方案:如果您知道自己的颜色范围有限,请尝试:

 [data-color=red] {background-color:red !important}
[data-color=blue] {background-color:blue !important}
[data-color=zophan-blue] {background-color:#33ccff !important}

如您所见,这允许灵活性,例如定义您自己的颜色;)

原文由 Niet the Dark Absol 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以从 html 传递 css 值:

 <button style="
    --tooltip-string: 'Ug. Tooltips.';
    --tooltip-color: #f06d06;
    --tooltip-font-size: 11px;
    --tooltip-top: -10px">
  Button
</button>

CSS:

 button::after {
  content: var(--tooltip-string);
  color: var(--tooltip-color);
  font-size: var(--tooltip-font-size);
}

来源: https: //css-tricks.com/css-attr-function-got-nothin-custom-properties/ codepen: https ://codepen.io/chriscoyier/pen/EbxVME

原文由 Romain Norberg 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题