如何设置固定宽度的html contentEditable div

Don*_*the 3 html css

我无法将contentEditable元素显示为一个固定的框(例如2个字符宽).因为它只是填充的宽度.当框中有文本时工作正常,但我希望有一个宽度为一的空盒子.有任何想法吗?

HTML:

<!DOCTYPE html>
<head>
<link rel="stylesheet" href="so.css" />
<body>
<h1 id="prompt">Type something in the box:</h1>
<h1 id="textarea"></h1>
</body>
Run Code Online (Sandbox Code Playgroud)

CSS:

#prompt, #textarea{
    display:inline;
}

#textarea{
    contentEditable: true;
    width: 2em; /* 20px doesn't work either */
    cursor: text;
    background-color:rgba(132, 225, 132, 0.9);
    border: 1px solid black;
    padding: 2px;
}
Run Code Online (Sandbox Code Playgroud)

Nen*_*car 5

首先,你必须设置contentEditable="true"HTML作为属性.

您可以使用Flexbox的,并设置min-width#textareaflex-shrink: 0;#prompt.所以#textarea会增长,但不会推动#prompt.

.content {
  display: flex;
}

#prompt {
  flex-shrink: 0;
}

#textarea {
  min-width: 100px;
  word-break: break-all;
  cursor: text;
  background-color:rgba(132, 225, 132, 0.9);
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div class="content">
  <h1 id="prompt">Type something in the box:</h1>
  <h1 contentEditable="true" id="textarea"></h1>
</div>
Run Code Online (Sandbox Code Playgroud)