Why does the browser display a new line as space?

For the longest time, I wanted to understand why the browser adds white space between rendered HTML elements when there is a NewLine between them, for example:

<span>Hello</span><span>World</span> 

In the above html, the string "HelloWorld" will be displayed without a space between "Hello" and "World", however in the following example:

 <span>Hello</span> <span>World</span> 

In the above html, the string "Hello World" will be displayed with a space between "Hello" and "World".

Now I have no problem with the fact that this is how it works, but something that hurts me a bit is that I always had the feeling that the spaces (or newlines) between the html elements do not matter at a time when the browser was displaying html to the user.

So my question is, does anyone know what the philosophical or technical reason for this behavior is.

Thank.

+45
html
Feb 25 '09 at 23:13
source share
5 answers

Browsers condense multiple whitespace characters (including newlines) into a single space when rendering. The one exception is the <pre> element, or those whose CSS white-space property is set to pre or pre-wrap . (Or in XHTML, the xml:space="preserve" attribute.)

+42
Feb 25 '09 at 23:15
source share

Spaces between block elements are ignored. However, spaces between inline elements are converted into one space. The reason is that inline elements may be interleaved with the regular inner text of the parent element.

Consider the following example:

 <p>This is my colored <span class="red_text">Hello</span> <span class="blue_text">World</span> example</p> 

Ideally, you want the user to see

 This is my colored Hello World example 

Removing spaces between two intervals will result in:

 This is my colored HelloWorld example 

But the same sample can be rewritten by the author (with OCD on HTML formatting :-)) as:

 <p> This is my colored <span class="red_text">Hello</span> <span class="blue_text">World</span> example </p> 

It would be better if it were shown sequentially with the previous example.

+47
Feb 25 '09 at 23:23
source share

HTML is set like this:

Line breaks are also space characters

http://www.w3.org/TR/REC-html40/struct/text.html#h-9.1

+11
Feb 25 '09 at 23:20
source share

If you have an a between the two tags, you expect it to display. In this case, you have the character "\ n" between the two tags; the behavior is similar and consistent ('\ n' is displayed as a single white space).

+1
Feb 25 '09 at 23:18
source share

Browsers make a mistake here:

http://www.w3.org/TR/html4/appendix/notes.html#hB.3.1

SGML (see [ISO8879], clause 7.6.1) indicates that line breaks immediately after the start tag should be ignored, since the line should be interrupted immediately before the end tag. This applies to all HTML elements without exception.

-one
Oct 03 2018-10-10
source share



All Articles