views:

124

answers:

5

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.

+1  A: 

New line is always translated into a space. It even gets worse on IE when every list item element is written in new line. Sad but true.

Eimantas
+1  A: 

I'm afraid you can't. Any group of white spaces is considered a space.

An alternative:

<h2>
    <a href="#" style="float: left;">Hello.</a>
    <span style="float: left;">World</span>
</h2>

But you will have another set of problems to solve due to to the floating elements.

o.k.w
+4  A: 

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>
Guffa
It is actually equivalent to:<h2> <p> test test </p> <p> test test </p></h2>
Ms2ger
@ms2ger: Yes, that's right, after just compacting white space. I made a clarification above.
Guffa
+5  A: 

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>
Ms2ger
+1. i've been forced to use this method at times, to maintain the correct output, but also have decent source code formatting.
nickf
Yep, this is annoying but common practice. Some templating languages have features to elided unwanted whitespace too.
bobince
A: 

Let's say HTML worked the way you want it to work. Then say I want the spaces. How would you have me create them? Add a special character like &nbsp; every time?

AmbroseChapel
I spone only about new lines.
Andy