Configure HTML element to behave like text character

51 Views Asked by At

Is it possible to configure an HTML element (custom element or built-in) to be treated like a single text (non-whitespace) character -- that is, it has an implied <nobr> wrapped around itself and adjacent text.

My use case is making certain musical symbols that are treated like text (like the sharp in F# but more complex). So I could write the note F<my-sharp></my-sharp> is nice and know that there would never be a line break between F and <my-sharp>, equivalent to the note <nobr>F<my-sharp></my-sharp></nobr> is nice. The css white-space: nowrap would configure anything inside <my-sharp> but not apply to the F behind it.

I want to avoid the <nobr> solution (which I've already implemented) in part because it breaks encapsulation to have a custom element manipulating the DOM of elements outside of it, and also because I am using this in a contenteditable block, so that if someone adds text after the F, like the note <nobr>F or G<my-sharp></my-sharp></nobr> is nice then the <nobr> is covering whitespace, which isn't intended.

A css attribute like display: inline-character does not seem to exist, but maybe there is another way?

1

There are 1 best solutions below

1
RoToRa On

I think on the one hand you are overthinking things here but on the other hand you aren't giving enough information on your actual problem. It may be an XY problem where you are asking about a perceived solution rather than your actual problem.

Some general things to consider:

You shouldn't be using the <nobr> element. It's deprecated. Neither should you create custom elements such as <my-sharp>, (unless you are creating web components). Instead use CSS white-space: nowrap on a suitable element with a class, such as <span class="note">...</span>

Also you don't need a custom element to display a sharp symbol. It can be used directly (F♯) or using an HTML entity: F&sharp; = F♯. And when doing this by default there can be no line break between the characters so you wouldn't need white-space: nowrap.

If the problem is about the user writing into the <span class="note">...</span> (or in your case the <nobr>...</nobr>) in a content editable element, it should be possible to programmatically prevent that.

Actually working with contenteditable can be quite tricky. Are you writing every thing yourself? It may be much easier to use one of several very capable existing components instead, for example, just to name one: CKEditor They provide ways for users to enter special characters such as and I believe some have features like only allowing specific text in an element.

If this doesn't help you need to show more of the actual problem you are trying to solve.