Why Does HTML Require That Multiple Spaces Show Up as a Single Space in the Browser

Why does HTML require that multiple spaces show up as a single space in the browser?

Spaces are compacted in HTML because there's a distinction between how HTML is formatted and how it should be rendered. Consider a page like this:

<html>
<body>
<a href="mylink">A link</a>
</body>
</html>

If the HTML was indented using spaces for example, the link would be preceded by several spaces.

How to stop Browser from replacing multiple space by single space?

Whitespace is non-significant by default, and is compacted down to a single space when rendered.

CSS can change that: white-space: pre-wrap will provide the default line-wrapping functionality that you would expect, plus the significant-whitespace behaviour of preformatted text. Best of both worlds!

How are multiple spaces showing in HTML, without pre, nbsp or white-space: pre?

I'm guessing that the offending space characters in your source code are not SPACE (U+0020), but are actually NO-BREAK SPACE (U+00A0). Visually, they appear identical, but if you view your source code in a hex editor (which shows you the individual bytes in the file), you'll see a different encoding for these characters.

Edit 1

This PHP code should find and replace the offending characters with regular spaces:

$strNoBreakSpace = mb_convert_encoding(' ', 'UTF-8', 'HTML-ENTITIES');
$strNormalSpace = mb_convert_encoding(' ', 'UTF-8', 'HTML-ENTITIES');

$strInput = str_replace( $strNoBreakSpace, $strNormalSpace, $strInput );

Edit 2

A simpler way of creating the two space characters:

$strNoBreakSpace = json_decode('"\u00A0"');
$strNormalSpace = json_decode('"\u0020"');

Replace continuous space with single space and multiple   elements

Try this,

string str = "<B>This is          Whitespace      Node </B>";
Regex rgx = new Regex("([\\S][ ])");
string result = rgx.Replace(str, "$1.")
.Replace(" .","?")
.Replace(" "," ")
.Replace("?"," ");

Tab space instead of multiple non-breaking spaces (nbsp)?

It's much cleaner to use CSS. Try padding-left:5em or margin-left:5em as appropriate instead.



Related Topics



Leave a reply



Submit