ajrlewis
ajrlewis

Reputation: 3058

Scrollable div within a div

I have two divs (content-title and content-items) embedded in a fixed div (content). I want the content div to hide anything that overflows it, the content-title div to be fixed in place but the content-items to be scrollable.

In the snippet below, the final <a> element is not visible and the content-items will not scroll vertically. Why is this, please?

.content {
  background: grey;
  max-height: 75px;
  overflow: hidden;
}

.content-title {
  color: blue;
}

.content-items {
  color: green;
  overflow-y: scroll;
}

.content-items a {
  display: block;
 }
 
 .content-items a:hover {
  background: green;
  color: grey;
 }
 
<div class="content">

  <div class="content-title">
    select a city:
  </div>

  <div class="content-items">
    <a>Foo</a>
    <a>Bar</a>
    <a>Baz</a>
  </div>
  
</div>

Upvotes: 2

Views: 59

Answers (2)

Zuber
Zuber

Reputation: 3483

  • set max-height to those div in which you need scrollable content.
  • in your case, you set max-height to content but you set the overflow-y to content-items.
  • set max-height to content-items instead of content

.content {
  background: grey;
  
  overflow: hidden;
}

.content-title {
  color: blue;
}

.content-items {
  color: green;
  overflow-y: scroll;
  max-height: 75px;
}

.content-items a {
  display: block;
 }
 
 .content-items a:hover {
  background: green;
  color: grey;
 }
 
<div class="content">

  <div class="content-title">
    select a city:
  </div>

  <div class="content-items">
    <a>Foo</a>
    <a>Bar</a>
    <a>Baz</a>
    <a>Foo</a>
    <a>Bar</a>
    <a>Baz</a>
  </div>
  
</div>

Upvotes: 3

Ingo Steinke
Ingo Steinke

Reputation: 951

The scrollable block needs a maximum height to give it a reason to scroll. In your example, .content-items displays in full height which might then be cut off by the parent's overflow: hidden.

I would rather set a maximum height on the .content-items only, like in the following modified example.

.content {
  background: grey;
}

.content-title {
  color: blue;
}

.content-items {
  color: green;
  max-height: 58px;
  overflow-y: scroll;
}

.content-items a {
  display: block;
 }
 
 .content-items a:hover {
  background: green;
  color: grey;
 }
 
<div class="content">

  <div class="content-title">
    select a city:
  </div>

  <div class="content-items">
    <a>Foo</a>
    <a>Bar</a>
    <a>Baz</a>
    <a>Foo</a>
    <a>Bar</a>
    <a>Baz</a>
  </div>
  
</div>

Upvotes: 1

Related Questions