Search code examples
cssdocument.writeletter-spacing

css letter spacing doesn't work when the page was rendered by document.write


Below code works as I expected. Every thing is perfectly styling.

<style>
   .letter-spacing{
      width: 400px;
      background: red;
      text-align: center;
      letter-spacing: 20px;
    }
</style>

<div class="letter-spacing">
   <img src="icon1.png">
   <img src="icon2.png">
</div>

result with letter-spacing

However, if I render the "div" using document.write, "letter-spacing: 20px;" doesn't work. The interesting thing is red background and center alignment still work.

<style>
   .letter-spacing{
      width: 400px;
      background: red;
      text-align: center;
      letter-spacing: 20px;
    }
</style>

<script>
    document.write('<div class="letter-spacing">'+
                       '<img src="icon1.png">'+
                       '<img src="icon2.png">'+
                   '</div>');
</script>

enter image description here

Is there anybody knows why?


Solution

  • it's because you write it like this

    document.write('<div class="letter-spacing">'+
                       '<img src="icon1.png">'+
                       '<img src="icon2.png">'+
                   '</div>');
    

    which will resulting in this HTML

    <div class="letter-spacing"><img src="icon1.png"><img src="icon2.png"></div>
    

    which doesn't contain any space, thus letter-spacing: 20px; not working.

    Different with the one you write directly in HTML with a new line which considered as a space.

    If you want to have the same results, then change it to this

    document.write('<div class="letter-spacing">'+
                       '<img src="icon1.png"> '+    // Note the space before '
                       '<img src="icon2.png">'+
                   '</div>');