How to make child div scrollable when it exceeds parent height?

后端 未结 3 875
情书的邮戳
情书的邮戳 2021-02-02 11:48

I have 2 child divs nested in a parent div in row-column pattern: the parent is a column, and the children are rows.\"enter

相关标签:
3条回答
  • 2021-02-02 11:50

    Because this post is still ranking very high in Google, I'd like to post a better solution using flexbox. Actually this is very simple. Use display: flex, flex-direction: column and overflow: hidden for parent and overflow-y: auto for child.

    .wrapper {
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    
    .scrollable-child {
      overflow-y: auto;
    }
    

    Here's the pen: https://codepen.io/pawelsas/pen/vdwjpj

    0 讨论(0)
  • 2021-02-02 11:50

    Use overflow property:

    .parent {
        width: 50px;
        height: 100px;
        border: 1px solid black;
        overflow: auto;
    }
    

    jsFiddle

    EDIT:

    if you want only second div to be scrollable, you need to change it height to 30px so child1 and child2 will exactly fit the parent height and add overflow property there:

    .parent {
        width: 50px;
        height: 100px;
        border: 1px solid black;
    }
    
    .child1 {
        height: 70px;
        background-color: red;
    }
    
    .child2 {
        height: 30px;
        background-color: blue;
        overflow: auto;
    }
    

    jsFiddle

    0 讨论(0)
  • 2021-02-02 12:14

    Overflow only works when you give it a value to overflow when greater than. Your value is relative to how big the top is, so using jQuery, grab that value then subtract from the parent.

    $(document).ready(function() {
      $(".child2").css("max-height", ($(".parent").height()-$(".child1").height()));
    });
    

    and add overflow's to the children

    .child1 {
        background-color: red;
        overflow: hidden;
    }
    
    .child2 {
        background-color: blue;
        overflow: auto;
    }
    

    http://jsfiddle.net/m9goxrbk/

    0 讨论(0)
提交回复
热议问题