Reputation: 25197
I am looking to use an HTML data attribute to assign a value
to a CSS property.
Essentially my HTML is like this:
<div class='dynamic-color' data-assigned-color='red'>lorem ipsum</div>
<div class='dynamic-color' data-assigned-color='blue'>lorem ipsum</div>
<div class='dynamic-color' data-assigned-color='green'>lorem ipsum</div>
And I want my CSS to be something like:
.dynamic-color {
color: [data-assigned-color];
}
My current working solution is:
.dynamic-color[data-assigned-color='red'] {
color:red;
}
...
However, there are several issues with this.
NOTE: I am using LESS so a LESS or pure CSS solution is good.
Upvotes: 10
Views: 22502
Reputation: 34177
At the moment, this is not fully possible without JavaScript.
When fully supported, you will be able to use data-attribute like this:
.dynamic-color {
color: attr(data-assigned-color);
}
As an alternative, have you considered something as simple as:
CSS
Set default colour options once in your stylesheet.
.red{color:red !important;}
.blue{color:blue !important;}
.green{color:green !important;}
HTML
Add/remove class as required to alter text colour. (I'm not sure what backend you are using but this could be done with your javascript or code behind).
<div class="dynamic-color red" data-assigned-color="red">lorem ipsum</div>
While attr()
is supported in most browsers for the content
property, CSS Values and Units. Level 3 adds the ability to use attr()
on any CSS property, and to use it for non-string values (e.g. numbers, colors).
FIREFOX (Partial support)
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
EDGE (Under consideration)
https://developer.microsoft.com/en-us/microsoft-edge/platform/status/csslevel3attrfunction/
CHROME (Partial Support)
The attribute selector can be used but I would recommend testing your code on all target browsers before using it in production.
Personally I would stick with JavaScript for the time being.
Upvotes: 8
Reputation: 7771
Try jQuery for this:
$('.dynamic-color').click(function() {
$(this).css('background', $(this).attr('data-assigned-color'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='dynamic-color' data-assigned-color='red'>lorem ipsum</div>
<div class='dynamic-color' data-assigned-color='blue'>lorem ipsum</div>
<div class='dynamic-color' data-assigned-color='green'>lorem ipsum</div>
As the comment below suggests, You can add a pure inline CSS solution like this:
<div class='dynamic-color' style="background:red;">lorem ipsum</div>
<div class='dynamic-color' style="background:blue;">lorem ipsum</div>
<div class='dynamic-color' style="background:green;">lorem ipsum</div>
Try using the style
attribute instead of the data-assigned-color
attribute.
Upvotes: 0