SHUBHAMR69
SHUBHAMR69

Reputation: 1

How do I set properties according to custom HTML attributes in CSS?

I'm working on Fractions.

My checkpoint is :

         
         frac {
             display: inline-block;
             position: relative;
             vertical-align: middle;
             letter-spacing: 0.001em;
             text-align: center;
             
         }
         
         frac {
             display: block;
             padding: 0.01em;
         }
         
         frac {
             border-top: thin solid black;
         }

It is working but I want to two things :

Btw, I only know CSS.

Upvotes: 0

Views: 223

Answers (1)

connexo
connexo

Reputation: 56754

There is no <frac> element in HTML.

To create your own <frac-el num="3" den="4"></frac-el>, you can create a small web component, which must adhere to custom element naming rules (name must contain a -). It also will need a closing tag.

That being said, here we go:

class FractionElement extends HTMLElement {
  numerator = document.createElement('sup');
  denominator = document.createElement('sub');
  style = document.createElement('style');
  
  constructor(n = 0, d = 1) {
    super().attachShadow({mode:'open'});
    this.num = n;
    this.den = d;
    this.style.textContent = `
      :host { display: inline-flex; flex-direction: column; text-align: center; }
      sup { border-bottom: 1px solid #666; }
    `;
    this.shadowRoot.append(this.numerator, this.denominator, this.style);
  }
  
  get num() { return this.numerator.textContent; }
  set num(val) { this.numerator.textContent = val; }
  
  get den() { return this.denominator.textContent; }
  set den(val) { this.denominator.textContent = val; }
  
  static get observedAttributes() {
    return ['num', 'den'];
  }
  
  attributeChangedCallback(attr, oldVal, newVal) {
    if (oldVal === newVal) return; // nothing to do, no change
    switch (attr) {
      case 'num': this.num = newVal ?? 0; break;
      case 'den': this.den = newVal ?? 1; break;
    }
  }
}

customElements.define('frac-el', FractionElement);
<frac-el num="3" den="4"></frac-el>
<frac-el num="11" den="27691"></frac-el>
<frac-el></frac-el>
<frac-el num="3x + 7" den="y"></frac-el>

Upvotes: 3

Related Questions