Home > Software engineering >  Trying to create a custom font-size attribute in html and pass it to CSS
Trying to create a custom font-size attribute in html and pass it to CSS

Time:10-16

I am trying to create a custom font-size attribute in html where the value I assign to the attribute is passed to the CSS file but it does not seem to be working

HTML:

<h1 fsize="4rem">TEST</h1>

CSS:

h1::after {
    font-size: attr(fsize);
}

I am trying to do it without using any classes, or style tags

CodePudding user response:

attr works only for content in most (?all) browsers at the moment.

You can use a CSS variable instead. i.e. have a style attribute rather than an fsize attribute. No need for further style tags.

h1::after {
  font-size: var(--fsize);
  content: 'I am the content of the after pseudo element';
}
<h1 style="--fsize:4rem;">TEST</h1>

Note: if you do ever want to use your own attribute then it should start with data-

CodePudding user response:

if you want attribute then you need javascript (at least in 2022)


but for now, you can do it with CSS vars (CSS only)

more details here enter image description here

h1::after {
  content: "hello world";
  font-size: var(--fsize);
}
<h1 style="--fsize: 2rem;"></h1>
<h1 style="--fsize: 5rem;"></h1>
<h1 style="--fsize: 10rem;"></h1>
<h1 style="--fsize: 3rem;"></h1>


still want the attribute?

function styleFsize() {
  const ATTR_NAME = "fsize";
  const allEl = document.querySelectorAll(`[${ATTR_NAME}]`);
  allEl.forEach(el => {
    el.style.setProperty(`--${ATTR_NAME}`, el.getAttribute(`${ATTR_NAME}`));
  })
}

styleFsize();
h1::after {
  content: "hello world";
  font-size: var(--fsize);
}
<h1 fsize="10rem"></h1>
<h1 fsize="5rem"></h1>
<h1 fsize="2rem"></h1>
<h1 fsize="1rem"></h1>

  • Related