I'm trying to use CSS attr()
to change background color of a pseudo :before
element.
<ul>
<li data-color="#ff0000">R</li>
<li data-color="#00ff00">G</li>
<li data-color="#0000ff">B</li>
</ul>
Here's the CSS
ul {
list-style: none;
}
li:before {
background-color: attr(data-color, color);
content: "";
display: inline-block;
height: 10px;
width: 10px;
}
But the before element doesn't show background color according to the data-color
attribute.
But when I add this CSS
li:after {
content: attr(data-color);
}
The :after
element shows the data-color
attribute content as the content.
Here's the JS fiddle http://jsfiddle.net/b7Rve/
What did I do wrong?
UPDATE
I just reread about color
in the Mozilla developer docs. It says that color
type is experimental. I guess I still need to wait until it's released.
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.
The CSS ::before selector can be used to insert content before the content of the selected element or elements. It is used by attaching ::before to the element it is to be used on. In the example above we are prepending an asterisk and a space before every paragraph element on the page.
In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Please, look at this other thread Setting width with CSS attr().
In short: "according to Mozilla Developer Network's documentation, is only compatible with the CSS content property [...], but cannot (yet) be used to generate values for other properties."
UPDATE MAY 16, 2016:
Looking at Mozilla Developer Network's documentation now is possibile but with caution:
The attr() function can be used with any CSS property, but support for properties other than content is experimental.
So, actually you can use it but surely browsers' support, altough better than in the past, is still only rare and experimental.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With