How to make child divs always fit inside parent div?

后端 未结 11 636
北海茫月
北海茫月 2020-12-08 09:13

My question is if there is a way, without using JavaScript, to cause child divs to extend to the borders of their parent, without exceeding those borders, when you cannot kn

相关标签:
11条回答
  • 2020-12-08 09:38

    In your example, you can't: the 5px margin is added to the bounding box of div#two and div#three effectively making their width and height 100% of parent + 5px, which will overflow.

    You can use padding on the parent Element to ensure there's 5px of space inside its border:

    <style>
        html, body {width:100%;height:100%;margin:0;padding:0;}
        .border {border:1px solid black;}
        #one {padding:5px;width:500px;height:300px;}
        #two {width:100%;height:50px;}
        #three {width:100px;height:100%;}
    </style>
    

    EDIT: In testing, removing the width:100% from div#two will actually let it work properly as divs are block-level and will always fill their parents' widths by default. That should clear your first case if you'd like to use margin.

    0 讨论(0)
  • 2020-12-08 09:40

    I had a similar problem, but in my case, I have content in my div that height-wise will exceed the boundaries of the parent div. When it does, I want it to auto-scroll. I was able to accomplish this by using

    .vscrolling_container { height: 100%; overflow: auto; }
    
    0 讨论(0)
  • 2020-12-08 09:43

    For closure, I think the answer to this question is that there is no solution. The only way to get the behavior I want is with javascript.

    0 讨论(0)
  • 2020-12-08 09:48

    you could use display: inline-block;

    hope it is useful.

    0 讨论(0)
  • 2020-12-08 09:53

    Make sure the outermost div has the following CSS properties:

    .outer {
      /* ... */
      height: auto;
      overflow: hidden;
      /* ... */
    }
    
    0 讨论(0)
提交回复
热议问题