0

So what I'm trying to do is map each character of a string to a span. With each span, I'm using inline styles in order to dynamically change the y position of the character based on the current position in the string. I then take this span string and add it to a variable which in the end will contain all of the characters converted to spans, and then output this into the DOM using innerHTML.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p id="output"></p>
  </body>
  <script>
    const text = "the dog jumped over the fence";

    let output = "";

    let i = 0;
    for (char of text) {
      output += `<span style="transform: translateY(${i}px)">${char}</span>`;
      i += 1;
    }

    document.querySelector("#output").innerHTML = output;
  </script>
  <style>
    body {
      background-color: black;
    }
    span {
      color: green;
    }
  </style>
</html>

However, none of my styles that have to do with transform are being applied externally. I've checked the developer console and the spans do indeed have the styles that I wanted, but they're not being applied on the actual page. [1] https://i.stack.imgur.com/MoDnq.png

The strange thing is this only seems to be happening for the transform CSS property. When I edit the font size for each span using the current position, I get the expected output.

/* When I change the for loop to adjust the font size instead of using transform */
for (char of text) {
      output += `<span style="font-size: ${i}px">${char}</span>`;
      i += 1;
    }

this is what I get: [1]: https://i.stack.imgur.com/0dk21.png

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

2 Answers2

0

When you attempt to translate the span elements vertically, you don't see a change because of how inline elements work in HTML.

If you want to apply a translation to the spans, you need to first change their display style to inline-block, which will let you apply a transformation to them while keeping them in the same line.

#output span { display: inline-block; }

From the w3 css wiki:

transformable element

A transformable element is an element in one of these categories:

  • all elements whose layout is governed by the CSS box model except for non-replaced inline boxes, table-column boxes, and table-column-group boxes [CSS2]

  • all SVG paint server elements, the clipPath element and SVG renderable elements with the exception of any descendant element of text content elements [SVG2]

skara9
  • 4,042
  • 1
  • 6
  • 21
0

CSS Transform only works on block element. Change your span into a block element.

span {
      display: inline-block;
      color: green;
    }
knicholas
  • 520
  • 4
  • 10