Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent HTML source formatting from affecting output?

It looks like extra line breaks in the HTML code may add unwanted spaces in the final output. I always thought that no matter how I layout my HTML code, it will not affect the way the rendered result looks like. But here is an example:

<h2>
    <a href="#">Hello.</a>World
</h2>

Will display: "Hello.World" - all looking good as expected

<h2>
    <a href="#">Hello.</a>
    World
</h2>

Will display: "Hello. World" - with an extra space after the dot!

Is there a chance to get rid of this effect? I want to have my code on separate lines - and not producing an extra space.

like image 544
Andy Avatar asked Nov 15 '09 09:11

Andy


2 Answers

You could use comments:

<h2>
    <a href="#">Hello.</a><!--
    -->World
</h2>

or put the spaces inside the tag:

<h2>
    <a href="#">Hello.</a
    >World
</h2>
like image 55
Ms2ger Avatar answered Oct 11 '22 12:10

Ms2ger


No, there isn't, not in this case.

In HTML all white space counts as spaces, but several white space characters after each other only counts as one. So, your code is equivalent to:

<h2> <a href="#">Hello.</a> World </h2>

The spaces adjacent to block elements are removed, but not spaces inside text. As the anchor tag is an inline element, it can't remove the space next to it, as that would change the content. So, after removing the spaces it can, this is what's left:

<h2><a href="#">Hello.</a> World</h2>

So, you can have extra white space anywhere you like, as long as it's not part of the content. This:

<h2    >

  <p >  test      test    </p     >

  <p   >  test       test  </p  >

</h2   >

Will be equivalent to (after removing spaces that doesn't affect the result):

<h2><p>test test</p><p>test test</p></h2>
like image 31
Guffa Avatar answered Oct 11 '22 12:10

Guffa