0

Is it possible to add some data attributes to a <figure> element and then access them from CSS?

For instance, I've tried

figure { margin: 0 attr(data-margin %); }

with

<figure data-margin="15">...</figure>

but it doesn't work.

Is there another way without using JS?

EDIT: I don't think my question is a duplicate. In fact, I'm looking for an alternative way to do this.

My goal is to decorate some elements in a page with attributes that then the end user can access and make use of by writing some CSS code. If that's impossible, I'll just ask them to write JS code, but that would be less safe, I think.

(The end users are ML researchers. I'm sure they can handle some CSS or JS code.)

Kiuhnm
  • 478
  • 3
  • 13
  • _“but it doesn't work”_ - check browser compatibility upfront next time, spares you being “surprised” like that. https://caniuse.com/#feat=css3-attr – CBroe Dec 05 '17 at 15:21
  • @CBroe So the only alternative is to use JS? – Kiuhnm Dec 05 '17 at 15:32
  • why set it in a data attribute? why not just apply an inline style instead? – Pete Dec 05 '17 at 15:34
  • @Pete I'm writing a LyX->html script. I want the information to be there, but the user should be able to ignore it if they want to. If I use an inline style, I'm forcing it on the user. – Kiuhnm Dec 05 '17 at 15:39
  • You are forcing it on the user if you put it into an attribute and then use that attribute in your css file? It's exactly the same as just putting it in an inline style rather than using an attribute in your css – Pete Dec 05 '17 at 15:41
  • @Pete The CSS code is written by the user, so they decide whether to use the attribute or not. – Kiuhnm Dec 05 '17 at 15:43
  • wow expecting end users to know css, good luck with that :0 – Pete Dec 05 '17 at 15:45

1 Answers1

-2

You can do it:

.test {
    display: inline-block;
    background-color: gray;
    width: attr(data-width px);
}

.test:after {
    content: attr(data-name);
}
<div class='test' data-name=" - CONTENT" data-width="200">teste</div>

but it does not work in Chrome: https://developer.mozilla.org/en-US/docs/Web/CSS/attr

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
maguri
  • 386
  • 2
  • 10
  • According to the MDN page you linked to, support for `attr` outside of `content` it is "No" or "?" for every browser. As far as I can tell, nothing at all supports it yet. It is a proposed feature from a draft spec. – Quentin Dec 05 '17 at 15:38
  • You cannot use attributes for anything other than content, that first item for width will not work in any browser – Pete Dec 05 '17 at 15:38
  • This appears to be the same as the code in the question anyway. What's the point of just repeating that? – Quentin Dec 05 '17 at 15:40