Search code examples
htmlcssscrollbarcontenteditable

How to show scrollbar in contenteditable div with max-height?


I have a div with the contenteditable tag set to true.
Also, I've added width, height, etc. using CSS.

Then this is the result:

#stringinput {
    min-width: 20em;
    min-height: 1.4em;
    max-width: 40em;
    max-height: 10em;
    padding: 0.3em 0.5em 0 0.5em;
    background-color: white;
    font-size: larger;
    text-align: left;
    border: 3px solid black;
    border-radius: 5px;
}
<div contenteditable="true" id="stringinput" spellcheck="false"></div>

It works fine, but when you are typing and you reach the max-height limit, the div expands downwards, but the border stays where it should be.

So, I want a scrollbar to appear when someone reaches the max-height limit, so that the div doesn't expand any further downwards. How can I do it?


Solution

  • Insert overflow-y: auto; Like This:

    #stringinput {
        overflow-y: auto;
       //More code
    }
    

    Full Code:

    #stringinput {
        min-width: 20em;
        min-height: 1.4em;
        max-width: 40em;
        max-height: 10em;
        padding: 0.3em 0.5em 0 0.5em;
        background-color: white;
        font-size: larger;
        text-align: left;
        border: 3px solid black;
        border-radius: 5px;
        overflow-y: auto;
    }
    <div contenteditable="true" id="stringinput" spellcheck="false">
    Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.Sample Text.
    </div>

    The overflow-y: auto property auto-enables the scrollbar when the max-height (y-axis) limit is reached.