Alex
Alex

Reputation: 2459

Non-breaking dash using css only

I have text that I'm displaying on a website that sometimes has dashes in it. In some html elements, I would like to keep the dashes from breaking (i.e. I always want the parts before and after the dash to stay on the same line). Normally you can do this using the non-breaking dash character ‑ in the html, but that's not an option for me because the website is in multiple languages which don't have dashes in the same places. I serve the text from the different languages by storing all the text bits for each language in a json file and when I put ‑ in those json strings, they just show up as the literal characters ‑. Is there a way to assert that just dashes are non-breaking using CSS only? The text still has to break on whitespace, so

white-space: nowrap;

won't work.

Upvotes: 0

Views: 182

Answers (1)

SirPilan
SirPilan

Reputation: 4857

Is there a way to assert that just dashes are non-breaking using CSS only?

No. In order to apply a different behavior you'd need to have a different element to apply styles to.

There is a way unsing css-classes and a little bit of js - have a look:

document.querySelectorAll('.non-breaking-hyphons').forEach(function(e) {
  e.innerHTML = e.innerHTML.replaceAll('-', '‑');
});
.text {
  width: 50px;
  border: 1px dashed black;
  padding: 5px;
}
<div class="text non-breaking-hyphons">
  this one is non-breakable
</div>

<div class="text">
  this one is still-breakable
</div>

<div class="text non-breaking-hyphons">
  this is another break-able test<br />
  this is <span>another</span> break-able test
</div>

Upvotes: 1

Related Questions