JSFiddle - React, Tailwind, and code Playground
HTML
<div onclick="addText()" style="cursor:pointer;">Click to add text</div><br>
<div id="terminal">CSS only<br>CSS only<br>CSS only<br>CSS only<br>CSS only<br></div>
<div id="closeBtn">X</div>
<div id="terminalUsingJs">With JS<br>With JS<br>With JS<br>With JS<br>With JS<br></div>
<div id="closeBtnUsingJs">X</div>
CSS
#terminal, #terminalUsingJs {
border: 2px solid;
overflow-y: auto;
height: 100px;
width: 200px;
}
#closeBtn, #closeBtnUsingJs {
--btn-width: 20px;
--scrollbar-width: 16px; /* just a guess */
background-color: red;
position: relative;
width: 20px;
top: -100px;
left: calc(200px - var(--btn-width));
}
JavaScript
const terminal = document.getElementById("terminal");
const terminalUsingJs = document.getElementById("terminalUsingJs");
addText = () => {
terminal.innerHTML += "overflowing line<br>";
terminalUsingJs.innerHTML += "overflowing line<br>";
// I want to get rid of this:
if (terminalUsingJs.scrollHeight > terminalUsingJs.clientHeight) {
document.getElementById("closeBtnUsingJs").style.left = 'calc(200px - var(--btn-width) - var(--scrollbar-width))';
}
}