0

I used to think line breaks don't have any effect in the rendering of html that's how minification works. But then I stumbled on something weird

<!DOCTYPE html>
<html>
<body>

<style>
div  { width: 200px; background: silver; margin: 30px; display: block!important; }
span { border: 1px solid yellow; display: inline!important; }
</style>

<!-- div1 -->
<div><span>Apple</span><span>Apple</span><span>Apple</span><span>Apple</span><span>Apple</span><span>Apple</span></div>

<!-- div2 -->
<div> 
<span>Apple</span>
<span>Apple</span>
<span>Apple</span>
<span>Apple</span>
<span>Apple</span>
<span>Apple</span>
</div>

</body>
</html>

Both div1 and div2 are identical except for former is minified and lacks newlines

As you can see spans in div2 line-up and wrap perfectly as inline elements are supposed to but in div1 they don't. Moreover I see some strange gap between <span>s

enter image description here

Any thoughts as to why it is so?

UPDATE:

So by helpful comments I got it why the spans don't wrap around because they have no space and therefore behave like a LONG WORD like

"lallalalalalallalalalalaalalalalalalalalalalalalallaalalalallallalalalalallalalalalaaaa"

which normally never wraps around and overflows container. Fixed it after realizing word-break: break-word works on spans too.

Vinay
  • 7,442
  • 6
  • 25
  • 48
  • 1
    Whitespace is collapsed into a single space. So newlines become a single space. That is, unless you use `white-space: pre-wrap;` or similar. – Niet the Dark Absol Apr 26 '20 at 08:54
  • I see but why the s don't wrap around? currently they just overflow outside div1 – Vinay Apr 26 '20 at 09:01
  • @Viney if the spans don't break in the first example, it's because there is no white space where it could break. Add `word-break: break-word` if you wish it to break anywhere. – Kaiido Apr 26 '20 at 09:07
  • Perfect...got it – Vinay Apr 26 '20 at 09:10

1 Answers1

0

The newlines you created in example 2 are being replaced with a single space.

Check out rules for replacement in the section on Inline formatting context at https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace

If you use a <pre> tag then you could preserve whitespace should you want to.

You could also do with with css white-space property https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

Kaiido
  • 123,334
  • 13
  • 219
  • 285
BizNuge
  • 938
  • 1
  • 8
  • 20