Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change pseudo :before background color using CSS attr()

Tags:

html

css

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.

like image 464
Petra Barus Avatar asked Apr 08 '14 02:04

Petra Barus


People also ask

What is attr () in CSS?

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.

What is :: before and :: after?

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.

How do you select before an element in CSS?

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.

What is CSS :: before?

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.


1 Answers

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.

like image 87
Luca Detomi Avatar answered Sep 23 '22 15:09

Luca Detomi