Issue
How can I use JavaScript to simulate the attr() function? For example I want to indent the following paragraph using the value of data-indent
as we do by p { text-indent: attr(data-indent em) }
.
<p data-indent=4>Hello World :-)</p>
EDIT: Most of you may not understand what I learned today because my question seems silly to you, but I think @G-Cyrillus's answer deserves more attention. Actually first I should mention that I was stupid not thinking about inline style. I thought it is neater to avoid that when you can use HTML class and id. But today I learned inline style is inevitable in some situations. This question was asked to solve my another question. Now I can easily use an HTML table to render a tree data structure without JavaScript in a neat manner.
Solution
From earlier comment :
okay, then the
var()
CSS option is the one that cost the less. You only have to ;)fill the attribute (style
insteaddata-X
) and a single rule inside the CSS sheet. ex: https://jsfiddle.net/d6Lbrq43/1/
You could avoid JavaScript if your attributes are filled on server side, you could use the style attribute to set a CSS variable that will be avalaible for that single element . see https://developer.mozilla.org/en-US/docs/Web/CSS/var to dig into it .
Here is an example (from the fiddle linked earlier) to demonstrate the idea:
* {/* here the demo is for a generic example of the effect on any tag */
text-indent: var(--indent);
/* this value can even be used for any other use */
background: linear-gradient(90deg, gray var(--indent), yellow var(--indent))
}
[style]:after {
content: attr(style);
background: green;
color: white;
}
<h1 style='--indent:4em'>Hello World :-)</h1>
<p style='--indent:2em'>Hello World :-)</p>
<p style='--indent:44em'>Hello World :-)</p>
<div style='--indent:12em'>Hello World :-)</div>
<p style='--indent:34em'>Hello World :-)</p>
<p style='--indent:0em'>Hello World :-)</p>
<p >Hello World :-)</p>
CSS var()
can have any value, and if this value is a number (with or without units) it can also be used for calculation inside a calc()
, set a font-size
, parts of a color, whatever you can think of ... as long as it can be inserted in a CSS rule.
Answered By - G-Cyrillus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.