Cacops Cacops - 3 months ago 16
Javascript Question

Non breaking space between two elements

I would like to ask, how to add non-breaking space at the end of first element so that the second element will stick to the first. I cannot use one element, because text in the first element is underlined, the second is not. So I have to use two spans, but I cannot figure out how to add non breaking space between them. (I want to have number to be at same line as lastText)



div {
width: 105px;
border: 1px solid #000;
}

span.a {
text-decoration: underline
}

span.b {
color: orange;
}

<div>
<span class="a">
Text, text, Text, Text, lastText
</span>
<span class="b">
(5)
</span>
</div>




Answer

Remember that in HTML, all whitespace (including newlines and indentation) collapses to a single space. So to do what you want, you need to not have any whitespace at the end of the first span, no whitespace after the end of its closing tag before the &nbsp; following it, no whitespace between the &nbsp; and the opening tag of the next span, and no whitespace at the beginning of the next span before the (5):

div {
  width: 105px;
  border: 1px solid #000;
}

span.a {
  text-decoration: underline
}

span.b {
  color: orange;
}
<div>
    <span class="a">
      Text, text, Text, Text, lastText</span>&nbsp;<span class="b">(5)
    </span>
</div>

That tends to hide the span in the source, though, which can be a pain from a maintenance perspective. So you'll frequently see people put the newline and indentation inside the tags:

div {
  width: 105px;
  border: 1px solid #000;
}

span.a {
  text-decoration: underline
}

span.b {
  color: orange;
}
<div>
    <span class="a">
      Text, text, Text, Text, lastText</span
    >&nbsp;<span class="b">(5)
    </span>
</div>