Home > other >  Get character corresponding to index number based on list-style-type CSS
Get character corresponding to index number based on list-style-type CSS

Time:11-29

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_ol_type_all_css

I want to extract the correct character based on the list-style-type and numerical index in CSS

For example, if I want the character for 3 in list-style-type: lower-greek; : γ

Example 2, I want the character for 9 in list-style-type: cjk-ideographic; : 九

Example 3, I want the characters 1,2,3 in list-style-type: lower-roman; : i,ii,iii

is there a way to do this easily with code?

I believe characters for 3 would have an index of 2, and characters for 9 would have an index of 8... since indexing starts at 0.

How do I return the correct character(s) for the number(s) I want, based on list-style-type?

CodePudding user response:

First Answer (CSS but no JS)

I believe you will have to use the n-th child selector, combined with list-style-type: 'γ. '; (mozilla docs)!

Checkout @ codepen: https://codepen.io/netrules/pen/yLzBMqK

<ul>
  <li>a, b, c, d</li>
  <li>e, f, g, h</li>
  <li>i, j, k, l</li>
  <li>...</li>
  <li>now i know my abc's!</li>
</ul>
ul {
  list-style-type: lower-greek;
}

li:nth-child(3) {
  list-style-type: 'γ. ';
}

I don't know if there is a better workaround though. I will check out again for future comments.

Second Answer

Upon second reading, I think what you might be referring to, is actually something similar to what's displayed in this css-tricks post. You can look up the pre-defined counter styles in this website and then write the corresponding javascript to evaluate and map them. Also relevant: unit tests for CSS3 Counter Styles in relation to browser kits [url].

Here's one way to do it: https://codepen.io/netrules/pen/KKXPWEo

const charmap = "900 ϡ, 800 ω, 700 ψ, 600 χ, 500 φ, 400 υ, 300 τ, 200 σ, 100 ρ, 90 ϟ, 80 π, 70 ο, 60 ξ, 50 ν, 40 μ, 30 λ, 20 κ, 10 ι, 9 θ, 8 η, 7 ζ, 6 στ, 5 ε, 4 δ, 3 γ, 2 β, 1 α";
const processedChars = charmap.split(", ");
const mapArray = processedChars.map(x => {
  let vals = x.split(" ");
  return {rem:vals[0], symbol:vals[1]};
})

function evalNumberToListKey(num) {
  let numCalc = num;
  let out = '';
  for(let element of mapArray) {
    const temp = numCalc%element.rem;
    if(temp !== numCalc) {
      numCalc = temp;
      out  = element.symbol;
    }
    if(numCalc === 0) {
      break;
    }
  }
  return out;
}

document.write(evalNumberToListKey(951));
  • Related