Sean Out
Sean Out

Reputation: 57

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?

Upvotes: 2

Views: 733

Answers (2)

Kyojimaru
Kyojimaru

Reputation: 2724

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>');

Upvotes: 3

Kamikaza
Kamikaza

Reputation: 635

It is very strange, but I could fix it in some hard way like this

document.write('<div class="letter-spacing"> '+
               '<img style="margin-right: 20px;" src="icon1">'+
                   '<img src="icon2">'+
               '</div>');

But if I set a class in css it does not work. Thats really strange

Upvotes: 0

Related Questions