How to make insertion into contentEditable paragraph bound by its size?

Viewed 18

I need an editable one line paragraph such that the text inserted into it must not overflow its size.

I'm currently using CSS to try to hide the overflow and also to avoid multiple lines (by not displaying the paragraph's children).

However, ideally I need the text inserted into the paragraph to be "cut" as soon as it would overflow.

This is my code so far (also in JSFiddle):

div
{
  width: 50vw;
  height: 50vh;
  margin: 10px auto;
  background-color: gray;
}

p
{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 25%;
  background-color: brown;
  text-align: center;
  
  white-space: nowrap;
  overflow-x: hidden;
}

/* Avoiding multiple lines */
p *
{
  display: none;
}
<div>
  <p contentEditable="true">
    Edit me! Unfortunally I can be overflowed... :(
  </p>
</div>

1 Answers

You can use word-break: keep-all; property in this case

div {
  width: 50vw;
  height: 50vh;
  margin: 10px auto;
  background-color: gray;
}

p {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 25%;
  background-color: brown;
  text-align: center;
  word-break: keep-all;
  white-space: normal;
}

p * {
  display: none;
}
<div>
  <p contentEditable="true">
    Edit me! Unfortunally I can be overflowed... :(
  </p>
</div>

Related