• When using the data-content attribut" />
  • When using the data-content attribut" />
  • When using the data-content attribut"/>

    CSS data-content attribute escapes backslashes

    921 Views Asked by At

    So, I have the following HTML structure:

    <ul>
    <li data-content="\ec00"></li>
    <li data-content="\ec01"></li>
    </ul>
    

    When using the data-content attribute in CSS to read the content:

    li:before { content: attr(data-content) }
    

    It shows ec00 and ec01 instead of those with backslashes.

    Any ideas how I could go about this?

    The idea behind is for a colorpicker for a huge amounts of icons.

    Thanks in advance, Dorian

    1

    There are 1 best solutions below

    1
    Terry On

    That is because you are using a character encoding that is not parsed properly in HTML. Remember that the CSS accesses the data- attributes as plaintext, and since HTML is does not parse hexadecimal characters, \ec00 is not parsed as it is supposed to be compared to when it is used as-is in a CSS file.

    What you could do is:

    • Use the character itself, i.e. '�' in the data- attribute
    • Use a numeric (decimal) equivalent, that will be parsed by the browser: &#60416; (because ec00 in hexadecimal is 60416 in decimals, and \ec00 is used to force parsing in CSS while &#...; is used to indicate a decimal entity in HTML)

    An example would be the copyright symbol:

    • Decimal: 169. In HTML, you will use &#169;
    • Hexadecimal: 00A9. In CSS, you will use \00A9 while in JS you will use \u00A9

    And here is a proof-of-concept demo:

    li:before { content: attr(data-content); margin-right: 1em; }
    <ul>
    <li data-content="&#169;">Using <code>&#169;</code>, parsed by HTML engine.</li>
    <li data-content="\u00A9">Using <code>\u00A9</code>, will not be parsed by HTML engine.</li>
      <li data-content="\00A9">Using <code>\00A9</code>, will not be parsed by HTML engine.</li>
    </ul>