43

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

I follow this instructions :

The attr() Function: Properties Values Collected from the Edited Document.

W3C

.bgborder {
  display: block;
  width: 5px;
  height: 100%;
  position: absolute;
  top: 0;
  background-color: attr(data-color color);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/brands.min.css" integrity="sha512-ym1f+T15aiJGZ1y6zs1XEpr8qheyBcOPqjFYNf2UfRmfIt5Pdsp7SD5O74fmsFB+rxxO6ejRqiooutodoNSjRQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />

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

Nothing appears...Am I right ?

In my chrome inspector I have this :

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

I don't understand why???

9 Answers 9

84

You can pass css values from html:

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

to css:

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Neat solution, here is browser support for that caniuse.com/#search=css%20v
This is great. The var is inherited by child elements too which is extra-awesome!
You make my day!
Beautiful hack. Quite elegant way around the lack of attr support!
55

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

screenshot of support table

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

6 Comments

s***... it's to bad... no other possibility to do that ? with less ? (but without jquery)
You mean other than style="background-color:#123456;"?
@Zagloo: With Less you can use loops to avoid repetition of code but the compiled CSS would still have to be the same way as mentioned above.
3 years later, still no support :p
Same it still doesnt support , sad when we have to theme the sites dynamically!
|
31

If you are talking only about colors, you can use currentColor value as a proxy.

For example:

.bgborder {
  background-color: currentColor;
  color: #FFF;
}
<td>
  <span class="bgborder" style="color: #e7663f">span</span>
  <i class="fa fa-copy"></i>
</td>

Comments

6

Currently, the CSS attr function can only be used with the content property in browsers

See here for compatibility

Per the CSS2 spec:

Limited to the content property

CSS3 will extend this (proposal)

..can be used on all properties; may return other values than <string>

Comments

4

alternately a very handy bit of javascript:

<P _my_colour="red" >one</P>
<P _my_colour="blue">two</P>
<P _my_colour="green">three</P>
<script>
    var my_col = document.querySelectorAll("[_my_colour]");
      my_col.forEach(element => {
        element.style.color = element.getAttribute("_my_colour");
    })

</script>

The css solutions outlined by other contributors are generally better and simpler, so a JS solution is somewhat reinventing the wheel, but does do explicitly what you want in the question, so it's here for completeness.

Comments

3

I guess that you are looking is CSS variables and you can use at Chrome, Firefox and Safari. Check the browser support at Can I use

And can see more at the video from Lea Verou

Comments

2

Somehow, it's always possible!. Example: Let's define a global variable in css:

:root {
  --theglobalvariable: coral;
}

In Javascript: Let's modify that global variable from javascript, assigning as value, the content of an element's attribute

var root = document.querySelector(':root');
root.style.setProperty('--theglobalvariable', document.getElementById('IdElement').getAttribute('NameOfAttribute'));

Now, in Css let's insert the value of the global variable into the element we want, and enjoy!

.someElement{
    color:var(--theglobalvariable);
}

Comments

2

I did find a new solution altough it doesn't work in EVERY browser: You can write you code like this to make it work:

background-color: attr(data-color type(<color>), #000);

In this way, the browser will get the property from the attribute data-color and know it's a color. It will also apply #000 is the attribute isn't defined.

The only problem with that line is that SCSS and SASS compilers might have issues with it, but I also found this workaround:

background-color: #{'attr(data-color type(<color>), #000)'};

Which forces SCSS to treat the line as a literal string and output it unchanged.

With that code, you can just create your HTML like so:

<div data-color="#fff" class="background-from-attr"></div>

Comments

0

declare variable in the scope (compatible with linter ):
ex:

        &.active {
            --data-color: attr(data-color type(<color>));
            background-color: var(--data-color);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.