Don Smythe
Don Smythe

Reputation: 9814

How to set html contentEditable div of fixed width

I am having trouble getting a contentEditable element to show as a box of a fixed with (eg 2 characters wide). As it is it is the width of the padding only. Works OK when there is text in the box, but I would like to have an empty box of a certain width. Any ideas?

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>

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;
}

Upvotes: 5

Views: 9667

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122155

First you have to set contentEditable="true" in HTML as attribute.

You can use Flexbox and set min-width to #textarea and flex-shrink: 0; to #prompt. So #textarea will grow but won't push #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;
}
<div class="content">
  <h1 id="prompt">Type something in the box:</h1>
  <h1 contentEditable="true" id="textarea"></h1>
</div>

Upvotes: 5

Emirhan &#214;zlen
Emirhan &#214;zlen

Reputation: 484

Inline elements can't have width or height. You should try to let them be at least inline-blocks.

Upvotes: 1

Related Questions