I want to add two Div in the page, one Div for the top part, which is ready-only, the other one Div for the lower part, which is editable. What I want to achieve is:
Here is the code I have:
<html>
<body>
<div>
<div>Top Part</div>
<div contenteditable="true">Click here to type</div>
</div>
</body>
</html>
In the code above, if I click on the lower Div, we can then type, then if we keep pressing Enter, it will show the vertical scroll bar, but if I scroll, the top Div will be scrolled up too, which I want to avoid.
So, how can I make the scroll bar only applied to the lower Div?
The scrollbar currently gets applied to the entire window, so all elements on the page scroll up and down together. One alternative is to make the editable area scrollable. Restrict the height of that area and set its overflow to "auto" or "scroll".
.edit {
max-height: 5em;
overflow-y: auto;
}
<div>
<div>Top Part</div>
<div contenteditable="true" class="edit">Click here to type</div>
</div>
You can avoid setting a specific height for the scrollable area by using the window height as the limiter. One method is to use flexbox so that the scrollable area fills the remaining window height. Here's an example. In your case, the <body>
can be the "outer" flexbox container.
In the demonstration below, the <body>
is split into two areas: the top area and a bottom "scrollable-container" area that fills the remaining window height. The bottom area limits the maximum height of the editable/scrollable area.
I also added a "placeholder" technique discussed here: Placeholder for contenteditable div.
html,
body {
margin: 0;
}
body {
height: 100vh;
display: flex;
flex-direction: column;
}
.header {
background-color: #EEF;
}
.scroll-container {
flex: 1;
min-height: 1em;
}
.scrollable {
max-height: 100%;
overflow-y: auto;
}
.header,
.scrollable {
padding: 0.5em;
box-sizing: border-box;
}
[contenteditable=true]:empty:before {
content: attr(data-placeholder);
color: grey;
font-style: italic;
cursor: text;
}
<div class="header">Top Part</div>
<div class="scroll-container">
<div contenteditable="true" class="scrollable" data-placeholder="Click here to type"></div>
</div>