2

On my page, I'm displaying a log file in a div element with overflow-y:auto. In the top right corner of the div, I'm overlaying a close button div with position:relative.

When the scrollbar appears, the button is overlaying the scrollbar which is hard to see and looks ugly. You can see an example here: https://jsfiddle.net/4azw0rLf/

Moving it with javascript when scrollHeight exceeds clientHeight feels like a hack. Is there an option in CSS to move the close button to the left for the width of the scrollbar as soon as it appears?

Dominic
  • 452
  • 4
  • 20
  • you can use `right:16px;` if your scrolling bar is 16px. `overflow-y:scroll` will always display the scrollbar or maybe this will help https://stackoverflow.com/a/4814526/13604954 – Patfreeze Sep 17 '21 at 12:42
  • Per your structure, I am not sure you can align it using css. However, if you can by any chance move the close button inside the div element, it should help you without having to write any css/js code. Only applying position absolute and right will do the trick. Check here https://jsfiddle.net/6n8sdb7u/ – Ganesh Pandhere Sep 17 '21 at 12:53
  • Can I ask why you removed my answer as the correct answer ? – Baro Oct 04 '21 at 14:15

1 Answers1

1

You can wrap your terminal and move your close button inside. I created a minimal example starting from your code.

EDIT

With the first answer the close button scrolled along with the text, I corrected using the position: sticky; and top:0px;

It is not compatible with all browsers, but with most, you can check compatibility here.

const terminal = document.getElementById("terminal");

addText = () => {
  terminal.innerHTML += "overflowing line<br>";
}
#container-terminal {
  position: relative;
  overflow-y: auto;
  border: 2px solid;
  height: 100px;
  width: 200px;
}

#terminal {
  position: absolute;
  height: 100%;
  width: 100%;
}

#closeBtn {
  background-color: red;
  position: -webkit-sticky;
  position: sticky;
  top:0px;
  width: 20px;
  display: inline-block;
  float: right;
}
<div onclick="addText()" style="cursor:pointer;">Click to add text</div><br>

<div id="container-terminal">
  <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>
Baro
  • 5,300
  • 2
  • 17
  • 39
  • With this setup, the close button is scrolled with the text - i.e. no longer accessible when the user scrolls to last line... Any idea on how to fix this? – Dominic Oct 05 '21 at 08:00
  • @Dominic You are right, I have corrected my answer. – Baro Oct 05 '21 at 12:26