Why does this happen?
This difference happens because, when displaying HTML, the browsers condense a sequence of blank characters (i.e. spaces, line breaks, etc) into a single space. This behavior is standard for any element that does not own the property white-space
defined as pre
or pre-wrap
.
In fact, that’s why, if you want to display more than one space, you can’t just use the space characters (
) in the markup, since, as we have seen, these are condensed. In this case, you can use several HTML entities
(non-breaking space). Behold:
body {
font-family: monospace;
}
A B <br />
|----|
How to indent my code and not have that space?
To remove spaces between spans, you should find some way to remove (or hide) the blank characters that exist between them in HTML (the line breaks and indentation spaces).
One way to do this is simply not to indent them, as done in the first example:
<div>
<span>1</span><span>2</span><span>3</span>
</div>
Another alternative is to use comments, as shown this answer soen:
<div>
<span>1</span><!--
--><span>2</span><!--
--><span>3</span>
</div>
Note that now all blank characters (in the example, line breaks and spaces) are now part of the comment, not the markup that will be displayed by browser.
If you can’t handle HTML, another option, using CSS, is to reduce the font size to zero for the <div>
(which contains the spaces) and set the normal size for each <span>
. Something like that:
.without-spacing {
font-size: 0;
}
.without-spacing span {
font-size: initial;
}
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<div class="without-spacing">
<span>1</span>
<span>2</span>
<span>3</span>
</div>
Note that, in this last example, we are not actually removing the blank characters, but hiding them with this little ruse. If you select them and "copy", you will see that there is still a space between each element. Therefore, use this alternative for visual purposes only.
makes sense to me, because between the span tags, there is some element (line break and space) only spaces before or after the tag would be disregarded
– h3nr1ke
@h3nr1ke, there is only the line break and the indentations there, but if you remove all the indents, it will still keep the space in bank, then it is the line break that causes the blank. And could you tell any source about the statement: "only spaces before or after the tag would be disregarded"?
– Fernando Leal
I don’t have a source... it was the test I did on your fiddle... but the explanations below were very complete and full of references V
– h3nr1ke