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

2022-01-22 00:00:00 html css twig less

我正在尝试在我的 css 中使用 data 属性为不同的元素添加颜色,但不起作用...

I'm trying to add color to different element with a data attribute in my css but doensn't work ...

我遵循以下说明:

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

什么都没有出现...我说的对吗?

Nothing appears...Am I right ?

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

In my chrome inspector I have this :

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

我不明白为什么...... ???

I don't understand why... ???

感谢您的帮助:)

推荐答案

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

Always a good idea to read the documentation: https://developer.mozilla.org/en/docs/Web/CSS/attr

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

Surprise! If nothing supports it, then it won't work ;)

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

Alternative: If you know you only have a limited range of colours, try:

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

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

As you can see, this allows flexibility, such as defining your own colours ;)

相关文章