Daniel Stephens
Daniel Stephens

Reputation: 3229

How to calculate distance from top of container until end of window via CSS?

I have a simple HTML layout with a few elements, and below a scrollable div container.

I don't know the size of unknown-height because the elements are generated dynamically, is there a simple way to make the div container scrollable, but set the height not exceeding the bottom of the window?

.scrollbar {
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #FF0000;
  overscroll-behavior-y: contain;
  height: calc(100vh - 100px) !important;
}
<p id="unknown-height">
  foo
</p>
<input type="text" />
<div class="scrollbar">
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
  <p>Foo</p>
</div>

Upvotes: 0

Views: 313

Answers (1)

alula
alula

Reputation: 111

Here you are:

parent container

  • use flexbox on container,
  • set height
  • flex-orientation to restore a vertical flow. -> in this way all child element will fill up the height of the container
  • add overflow hidden to hide stuff that would normally need more space

scrolling child

  • set overflow scroll to you child element

NB I added border colors to check easly the final result.

.your-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  border: 1px solid blue;
}

.scrollbar {
  overflow-y: scroll;
  border: 1px solid red;
}
<div class="your-container">
  <p id="unknown-height">
    foo
  </p>
  <input type="text" />
  <div class="scrollbar">
  scrollbar
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
    <p>Foo</p>
  </div>
</div>

Upvotes: 2

Related Questions