2

HTML example:

<div data-style-top="20%">Hi, I'm not so high right now.</div>

Here, I want the div with 'data-style-top' attribute which is set to '20%' to have a css property of top:20%; If the attribute value was 50% then top property should have the value '50%'.

Any ways to achieve this? Like:

div[data-style-top]:before {
 top: content(attr(data-style-top));
}

Sorry if I couldn't explain properly. I suck at explaining.

3
  • cannot with only css, with jquery $('[data-style-top]').data('style-top') Commented Nov 24, 2013 at 9:13
  • Do you want it to work for all data-style-XXX attributes? So like if it had data-style-width="40px", it would also recognize that? It's also possible with jQuery, though a bit more difficult than just top. Commented Nov 24, 2013 at 9:20
  • TIL using attr() value for another property than content is part of a CSS3 module (for now) but is unsupported (for now). Source: MDN (edit: comment in bugzilla says it should work in IE9+. Can't test this today) Commented Nov 24, 2013 at 9:20

2 Answers 2

2

Beware! Browser support might be bad.

In CSS Values and Units Module Level 3 (which is currently a Candidate Recommendation), the syntax for attr() would be:

div[data-style-top] {
  top: attr(data-style-top %);
}

You could also provide a fallback value, if the data-style-top attribute doesn’t have a value:

div[data-style-top] {
  top: attr(data-style-top %, 10);
}
  • data-style-top is the HTML attribute to be used
  • % is the CSS type/unit to be used
  • 10 is the fallback (= 10%)

Note that attr() is "at-risk and may be dropped during the CR period".

This week a new CR (2013-11-21) was published, which, for whatever reason, is not yet public, aside from the Editor’s Draft namespace. attr() is still included, but again listed as "at-risk".

Sign up to request clarification or add additional context in comments.

Comments

-1

Another solution here :

Fiddle : http://jsfiddle.net/zTv8s/1/

$(document).ready(function() {
    alert('before : ' + $("*[data-style-top]").attr("data-style-top")); // for demo : 20%
           $("*[data-style-top]").attr("data-style-top","50%");
    alert('after : ' + $("*[data-style-top]").attr("data-style-top")); // for demo : 50%

});

Variant with a for each and a specific id : http://jsfiddle.net/zTv8s/3/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.