using html data-attributes as css-variable (i.e. text-shadow)
Asked Answered
A

1

15

i'm trying to use inline data-attributes as variables for css... is there any known option to get this run:

.mycss-class {text-shadow: attr(data-textshadow); }
<div class="mycss-class" data-textshadow="0 0 0 #000">lorem ipsum</div>

chrome dev-tool just reports "invalid property value"

many thanks & kind regards

Alumroot answered 20/9, 2017 at 13:16 Comment(5)
from developer.mozilla.org/en-US/docs/Web/CSS/attr: Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental. In other words, attr cannot be used with anything other than content:, if at allAsleyaslope
If you are putting it into a data attribute, why not just bang it straight into a style attribute instead?Asleyaslope
thank you, i already had feared it... the example was just a tiny version of a more complex construct. so "lorem ipsum" represents a hand full of dom nodes :)Alumroot
But if you are outputting that shadow into the data attribute, you can just change that data attribute to be style="text-shadow: 0 0 0 #000" and that will give that element the text shadow you are after? Or am I missing the pointAsleyaslope
the point is - i try to avoid inline-styles and keep a good content/code-ratio... if i can do without, ill do :) what i wanted, was "data-cstcolor="#dce568" and use this for textshadows, hovereffects, background-colors... and so on :) it will not work, but it would have been a nice clean solution... so... thanks again :) i guess i'll have to wait for css4 :DAlumroot
A
26

You can do this with CSS Custom Properties.

Support is pretty good, including Edge (but no IE)

p {
  width:80%;
  margin:1em auto;
  text-shadow: 2px 6px 2px grey;
}

p.colored {
  color: var(--mycolor)
}

p.shadowed {
  text-shadow: 2px 6px 2px var(--shadowcolor);
}
<p class="colored" style="--mycolor:red;">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quibusdam numquam aut aperiam excepturi id quaerat, fugiat, impedit natus maxime voluptates officia? Fuga earum quis exercitationem et fugiat, amet nam officiis?</p>

<p class="shadowed" style="--shadowcolor:green;">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quibusdam numquam aut aperiam excepturi id quaerat, fugiat, impedit natus maxime voluptates officia? Fuga earum quis exercitationem et fugiat, amet nam officiis?</p>
Ariose answered 20/9, 2017 at 15:46 Comment(2)
nice! thnx @ArioseAlumroot
Is it possible to do the opposite? As in, use css variables in the html attributes?Craps

© 2022 - 2024 — McMap. All rights reserved.