Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autosize contenteditable element?

Here is my contenteditable element:

    #editor {
        width: 200px;
        height: 30px;
        border: 1px solid red;
        overflow: hidden;
    }
    <div id="editor" contenteditable="true"></div>

I want it can autosize according to the user's content. I try to listen to keyup event:

    editor.addEventListener("keyup", function (){
        newheight = editor.scrollHeight;
        editor.style.height = newheight + "px";
    })   

this could work when the div grow higher, but when user delete all content, the div can't be shorter.

How can I let it be autosize?

DEMO here

like image 200
hh54188 Avatar asked Nov 20 '25 05:11

hh54188


1 Answers

Add "display: inline-block;" to your CSS and and "min-" to width and height.

Your DIV will automatically grow the innerHTML content.

<html>
  <style type="text/css">
    #Test
    {
      display: inline-block;
      min-width: 30px;
      min-height: 30px;
      border: 1px solid red;
      overflow: hidden;
    }
  </style>
  <div id="Test" >
    Nothing But Bigger
    And <br />
    Taller
  </div>
</html>
like image 163
IT Serenity Avatar answered Nov 21 '25 19:11

IT Serenity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!