Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I stop browsers from collapsing whitespace across span boundaries?

I’m trying to render some text using spans with borders to show groupings. But if one span ends in whitespace, then the browser ignores any whitespace outside the span as well, and the borders get mashed up against each other.

I can see that usually those spaces are visually adjacent, so I’m not sure it’s technically a rendering bug, but in this case it feels like one since there’s a border in between that makes the difference visible.

Regardless of whether it’s a bug, is there an easy work-around to prevent this? I do normally want white-space to collapse and wrap as usual, so… I guess I could write code to collapse white-space myself and use pre-wrap but I’d rather not if I don’t have to.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note that I do want to put the borders right next to each other sometimes, when there’s not supposed to be a space between.

Here’s a minimal example. Note how the first two spans are separated slightly, but since the second one ends with a space inside the span, the second and third are mashed together.

<style>span { padding: 1ex;  border: thin solid black; }</style>
<p><span>span</span> <span>span_ </span> <span>span</span></p>

I’m… a little lost as to where to even start looking on this one. I could put a non-breaking space between spans, but then that prevents it from wrapping there. I guess I could put the white space between spans and then follow it with a non-breaking space? Or… hmm. Replacing the final space inside the span with a non-breaking space also gives me the behavior I want.

But I’m really hoping there’s some kind of styling setting that’ll make the browser treat span breaks as substantial so I don’t have to add another text processing step.

>Solution :

span tags are inline by default, so apparently the two whitespaces are "merged" into one by the browser.

But if you define them as inline-blocks, the whitespace between them appears as desired:

span {
  display: inline-block;
  padding: 1ex;
  border: thin solid black;
}
<p><span>span</span> <span>span_ </span> <span>span</span></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading