Fix an element horizontally, but not vertically with css

Viewed 125

I have an overlay element in a container which scrolls horizontally.

I want this overlay to be fixed in place horizontally, but if I scroll the window, the overlay should scroll along with the page. https://jsfiddle.net/Lvy9uq0n/1/

.box {
  height: 300px;
  width: 3000px;
  background: white;
  border: 1px solid black;
}

.overlay {
  position: fixed;
  left: 50%;
  padding: 10px;
  width: 200px;
}

html,
body {
  height: 1000px;
}

.container {
  overflow-x: scroll;
}
<div class="container">

  <div class="box">
    <div class="overlay">
      Overlay

    </div>
  </div>

</div>
<div syle="height:1000px">

  Test
</div>

TLDR: Element should be fixed inside a container horizontally but not vertically

1 Answers

It sounds like you want to take the overlay div out of the normal flow of the document, which is why I suppose you used the position: fixed class. However, that takes the element out of the document flow and it fixes the vertical position relative to the browser window.

Try position: absolute to position your overlay outside the flow, but still have it scroll normally with the document. You can center it using left: 0; right: 0 and margin: auto. I'm not sure how far you'd like the overlay from the top:

.overlay {
  position: absolute;
  top: 10vh;
  left: 0; right: 0;
  margin: auto;
  padding: 10px;
  width: 200px;
}
Related