I have two divs: a div with a Text Field and a div with a long list of items. My use case is to keep the search box (text field) at the top while the listContainer
div can scroll if it contains a large number of items. Currently, the scroll bar is added to the entire parent div, so the search box is hidden as you scroll. I only need the scrollbar for the list container.
The problem is solved if I know the height of the search container and parent (listContainer height = parent height — searchContainer height). Is there a way to compute the height of the list container using CSS?
.parent {
height: 100%
}
.searchContainer {}
.listContainer {
height: 90%;
}
<div class="parent">
<div class="searchContainer">
<input placeholder="Enter search string">
</div>
<div class="listContainer">
<div class="list-item">1</div>
<div class="list-item">2</div>
<div class="list-item">3</div>
<div class="list-item">4</div>
<div class="list-item">5</div>
<div class="list-item">6</div>
<div class="list-item">7</div>
<div class="list-item">8</div>
<div class="list-item">9</div>
<div class="list-item">10</div>
<div class="list-item">11</div>
<div class="list-item">12</div>
<div class="list-item">13</div>
<div class="list-item">14</div>
<div class="list-item">15</div>
<div class="list-item">16</div>
</div>
</div>
2
Answers
One way to solve this would be to position the
.searchContainer
absolutely within the parent container, and add some top padding to thelistContainer
to push it down below the input.Consider
position:sticky;
MDN link for more info
Add
to your css and it will "stick" to the top. If you don’t want it to move at all, then tweak the
top:0;
setting.